package com.cn.fdapfe.common.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CsvToJsonParseruTILS {

    public static String parseCsvToJson(String filePath) {
        List<Map<String, String>> dataList = new ArrayList<>();
        String line;
        String[] headers = null;

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            // 读取CSV文件的第一行作为表头
            if ((line = br.readLine()) != null) {
                headers = line.split(",");
            }

            // 逐行读取数据并转换为Map
            while ((line = br.readLine()) != null) {
                String[] values = line.split(",");
                if (headers != null && values.length == headers.length) {
                    Map<String, String> rowMap = new HashMap<>();
                    for (int i = 0; i < headers.length; i++) {
                        rowMap.put(headers[i], values[i]);
                    }
                    dataList.add(rowMap);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        // 将List转换为JSON格式字符串
        return convertToJsonString(dataList);
    }

    private static String convertToJsonString(List<Map<String, String>> dataList) {
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("[");

        for (int i = 0; i < dataList.size(); i++) {
            Map<String, String> rowMap = dataList.get(i);
            jsonBuilder.append("{");

            int entryCount = 0;
            for (Map.Entry<String, String> entry : rowMap.entrySet()) {
                jsonBuilder.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\"");
                if (entryCount < rowMap.size() - 1) {
                    jsonBuilder.append(",");
                }
                entryCount++;
            }

            jsonBuilder.append("}");
            if (i < dataList.size() - 1) {
                jsonBuilder.append(",");
            }
        }

        jsonBuilder.append("]");
        return jsonBuilder.toString();
    }

    public static void main(String[] args) {
        String filePath = "E:\\算法平台诊断算法样例数据\\test.csv"; // 替换为实际的CSV文件路径
        String jsonResult = parseCsvToJson(filePath);
        System.out.println(jsonResult);
    }
}
