0

I am having a JSON file with the data as below format

{"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

sum_message_count api_product response_status_code 66 Test1 200 8 Test2 201 2 Test3 201 22 Test4 201

Can someone help on the code snippet in java (main program)

2

1 Answer 1

0
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 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.