D
D
DeNissss44442021-11-13 19:00:41
Java
DeNissss4444, 2021-11-13 19:00:41

Why is the information itself not in JSON format when writing information to a JSON file?

I wrote a method that receives JSON, converts it to a Java object and writes it to FIle.json. The problem is that in the file itself (FIle.json) it is not displayed in the usual JSON form, but here's how

"[\n  {\n    \"userId\": 1,\n    \"id\": 1,\n    \"title\": \"sunt aut facere repellat provident occaecati excepturi optio reprehenderit\",\n ...

And all this goes in one line ... Why this is happening, I do not quite understand. Here is the method code
public static void getRequest(String url, String path) {
        PostDTO postDTO = new PostDTO();
        String pathJSONFile = "src/main/resources/allPost.json";
        List<PostPojo> postPojos = null;


        HttpRequest request = HttpRequest.newBuilder()
                .GET()
                .header("accept", "application/json")
                .uri(URI.create(url + path))
                .build();

        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            ObjectMapper objectMapper = new ObjectMapper();

            postPojos = objectMapper.readValue(response.body(), new TypeReference<List<PostPojo>>() {
            });
            objectMapper.writeValue(Paths.get(pathJSONFile).toFile(), response.body());
            postDTO.setStatus(response.statusCode());
            postDTO.setPosts(postPojos);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

When I output response.body() through System.out.println , I see what it outputs to the console in the usual JSON form. Tell me what could be the reason?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BorLaze, 2021-11-13
@DeNissss4444

objectMapper.writeValue(Paths.get(pathJSONFile).toFile(), response.body());

Because you are writing a string (response.body()), not a list of objects (postPojos).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question