1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- package com.phm.manage.util;
- import cn.hutool.core.io.FileUtil;
- import cn.hutool.json.JSONArray;
- import cn.hutool.json.JSONObject;
- import cn.hutool.json.JSONUtil;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.phm.manage.domain.common.CommonResult;
- import lombok.extern.slf4j.Slf4j;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.stream.Collectors;
- /**
- * @Description JsonUtils
- * @Author WGK
- * @Date 2023/10/10 22:33
- */
- @Slf4j
- public class JsonUtils {
- /**
- * 返回值转JSON
- *
- * @param commonResult 公共返回值
- * @return 结果
- * @throws JsonProcessingException Exception
- */
- public static String convertJson(CommonResult commonResult) throws JsonProcessingException {
- ObjectMapper objectMapper = new ObjectMapper();
- return objectMapper.writeValueAsString(commonResult);
- }
- /**
- * json 转 csv
- *
- * @param jsonArray 数组
- * @return csv 结果
- */
- public static List<String> jsonArrayToCsv(JSONArray jsonArray) {
- // 获取CSV的表头
- List<String> headers = new ArrayList<>(jsonArray.getJSONObject(0).keySet());
- // 构造CSV行列表
- List<String> csvLines = jsonArray.stream().map(jsonObject -> {
- StringBuilder line = new StringBuilder();
- for (String header : headers) {
- // 根据表头获取对应的值,并追加到CSV行中
- line.append(((JSONObject) jsonObject).get(header)).append(",");
- }
- // 移除末尾的逗号
- return line.substring(0, line.length() - 1);
- }).collect(Collectors.toList());
- // 在CSV行列表开头添加表头
- csvLines.add(0, String.join(",", headers));
- return csvLines;
- }
- /**
- * json转csv文件
- *
- * @param jsonString data
- * @param csvFilePath path
- */
- public static void jsonToFileCsv(String jsonString, String csvFilePath) {
- try {
- // 将JSON字符串转换为JSON数组
- JSONArray jsonArray = JSONUtil.parseArray(jsonString);
- // 将JSON数组写入CSV文件
- FileUtil.writeUtf8Lines(JsonUtils.jsonArrayToCsv(jsonArray), csvFilePath);
- } catch (Exception e) {
- log.info("json转csv文件错误:{}", e.getMessage());
- }
- }
- /**
- * csv文件转Json
- *
- * @param csvFilePath path
- */
- public static String fileCsvToJson(String csvFilePath) {
- // TODO csv文件转Json
- return "";
- }
- }
|