|
@@ -0,0 +1,55 @@
|
|
|
+package com.phm.manage.util;
|
|
|
+
|
|
|
+import cn.hutool.json.JSONArray;
|
|
|
+import cn.hutool.json.JSONObject;
|
|
|
+import com.fasterxml.jackson.core.JsonProcessingException;
|
|
|
+import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
+import com.phm.manage.domain.common.CommonResult;
|
|
|
+
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.List;
|
|
|
+import java.util.stream.Collectors;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @Description JsonUtils
|
|
|
+ * @Author WGK
|
|
|
+ * @Date 2023/10/10 22:33
|
|
|
+ */
|
|
|
+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;
|
|
|
+ }
|
|
|
+}
|