有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何使用java将连续的JSON对象转换为csv

我有一个JSON文件,数据格式如下

{"sum_message_count":"66","api_product":"Test1","response_status_code":"200"}
{"sum_message_count":"8","api_product":"Test2","response_status_code":"201"}
{"sum_message_count":"2","api_product":"Test3","response_status_code":"201"}
{"sum_message_count":"62","api_product":"Test4","response_status_code":"201"}


So I want these JSON objects into csv as following

汇总信息计数api产品响应状态代码 66测试1200 8测试2 201 2测试3 201 22测试4 201

有人能帮我用java(主程序)编写代码片段吗


共 (1) 个答案

  1. # 1 楼答案

    String input = "[" +
                "{\"sum_message_count\":\"66\",\"api_product\":\"Test1\",\"response_status_code\":\"200\"},\n" +
                "{\"sum_message_count\":\"8\",\"api_product\":\"Test2\",\"response_status_code\":\"201\"},\n" +
                "{\"sum_message_count\":\"2\",\"api_product\":\"Test3\",\"response_status_code\":\"201\"},\n" +
                "{\"sum_message_count\":\"62\",\"api_product\":\"Test4\",\"response_status_code\":\"201\"}" +
                "]";
        List<String> headers = Arrays.asList("sum_message_count", "api_product", "response_status_code");
        ObjectMapper mapper = new ObjectMapper();
        List<Object> messages = mapper.readValue(input, List.class);
        StringBuilder data = new StringBuilder();
        for (int i = 0; i < messages.size(); i++) {
            LinkedHashMap<String, String> msg = (LinkedHashMap<String, String>) messages.get(i);
            data.append(String.format("%s %s %s ",
                    msg.get(headers.get(0)),
                    msg.get(headers.get(1)),
                    msg.get(headers.get(2))));
        }
    
        System.out.println(headers);
        System.out.println(data.toString());
    
      //write file here