JsonUtils.java 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package com.phm.manage.util;
  2. import cn.hutool.core.io.FileUtil;
  3. import cn.hutool.json.JSONArray;
  4. import cn.hutool.json.JSONObject;
  5. import cn.hutool.json.JSONUtil;
  6. import com.fasterxml.jackson.core.JsonProcessingException;
  7. import com.fasterxml.jackson.databind.ObjectMapper;
  8. import com.phm.manage.domain.common.CommonResult;
  9. import lombok.extern.slf4j.Slf4j;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import java.util.stream.Collectors;
  13. /**
  14. * @Description JsonUtils
  15. * @Author WGK
  16. * @Date 2023/10/10 22:33
  17. */
  18. @Slf4j
  19. public class JsonUtils {
  20. /**
  21. * 返回值转JSON
  22. *
  23. * @param commonResult 公共返回值
  24. * @return 结果
  25. * @throws JsonProcessingException Exception
  26. */
  27. public static String convertJson(CommonResult commonResult) throws JsonProcessingException {
  28. ObjectMapper objectMapper = new ObjectMapper();
  29. return objectMapper.writeValueAsString(commonResult);
  30. }
  31. /**
  32. * json 转 csv
  33. *
  34. * @param jsonArray 数组
  35. * @return csv 结果
  36. */
  37. public static List<String> jsonArrayToCsv(JSONArray jsonArray) {
  38. // 获取CSV的表头
  39. List<String> headers = new ArrayList<>(jsonArray.getJSONObject(0).keySet());
  40. // 构造CSV行列表
  41. List<String> csvLines = jsonArray.stream().map(jsonObject -> {
  42. StringBuilder line = new StringBuilder();
  43. for (String header : headers) {
  44. // 根据表头获取对应的值,并追加到CSV行中
  45. line.append(((JSONObject) jsonObject).get(header)).append(",");
  46. }
  47. // 移除末尾的逗号
  48. return line.substring(0, line.length() - 1);
  49. }).collect(Collectors.toList());
  50. // 在CSV行列表开头添加表头
  51. csvLines.add(0, String.join(",", headers));
  52. return csvLines;
  53. }
  54. /**
  55. * json转csv文件
  56. *
  57. * @param jsonString data
  58. * @param csvFilePath path
  59. */
  60. public static void jsonToFileCsv(String jsonString, String csvFilePath) {
  61. try {
  62. // 将JSON字符串转换为JSON数组
  63. JSONArray jsonArray = JSONUtil.parseArray(jsonString);
  64. // 将JSON数组写入CSV文件
  65. FileUtil.writeUtf8Lines(JsonUtils.jsonArrayToCsv(jsonArray), csvFilePath);
  66. } catch (Exception e) {
  67. log.info("json转csv文件错误:{}", e.getMessage());
  68. }
  69. }
  70. /**
  71. * csv文件转Json
  72. *
  73. * @param csvFilePath path
  74. */
  75. public static String fileCsvToJson(String csvFilePath) {
  76. // TODO csv文件转Json
  77. return "";
  78. }
  79. }