0

I want to write the rest response of my endpoint that is a json in a file from controller i'm returning JSONArray OBJ in response

  [
            {
                "_fields": {
                  "key1":"value1",
                    "key2","value2"
                }
            },
            {
                "_fields": {
                    "key1":"value1",
                    "key2","value2"
                }
            },
            {
                "_count": 12,
                "links": [
                    {
                        "rel": "prev",
                        "href": "http://localhost:8080/someprevurl"

                    },
                    {
                        "rel": "next",
                        "href": "http://localhost:8080/somenexturl"


                    },
                    {
                        "rel": "self",
                        "href": "http://localhost:8080/selfurl"
                    }
                ]
            }
        ]

I've override the to string methods this is my method where i'm trying to write the jsonarray into the file

public static void generateFile(JSONArray fileContent, String directory, String fileName, String extension) {
    logger.info("Writing into the file : {}{} start time : {}", fileName, extension, Instant.now());
    try {
        FileWriter file = new FileWriter(directory + fileName + extension);

        file.write(fileContent.toJSONString());
        file.flush();
    } catch (IOException e) {
        logger.error("Exception generated while generating file : {}", e.getMessage());

    }
}

but after using toJSONString the response in file is like this

[
        {
            "_fields": MyDTONAME [
              key1=value1,
                key2="value2"
            ]
        },
        {
             "_fields": MyDTONAME [
              key1=value1,
                key2="value2"
            ]
        },
        [
            "_count": 12,
    links: [.......]
        ]
    ]

do i need to define the complete format like replacing [] to {} & = to :.jsonstring is not suppose to do that "" also missing so what to i do ? Please suggest

Himanshi
  • 84
  • 1
  • 2
  • 13
  • *"I've override the to string methods"* Why? Why not let Gson do its job of rendering the correct JSON? – Andreas Mar 05 '20 at 08:43
  • I am however very confused how your code compiles, given that Gson's class is named `JsonArray`, and you seem to be using a class named `JSONArray`. – Andreas Mar 05 '20 at 08:45
  • You need to fix json error first, you can use JSON Formatter & Validator Tool like: https://jsonformatter.curiousconcept.com/ – Houssin Boulla Mar 05 '20 at 09:19
  • @Andreas M using org.json.simple.JSONArray – Himanshi Mar 05 '20 at 10:04
  • @Andreas iusing {${member.name()}":"${member.value}", "${otherMembers}"} template format i format my tostring seems working what is a better approach – Himanshi Mar 05 '20 at 10:06
  • @Himanshi *"M using **org.json.simple**.JSONArray"* Then **why** did you tag [tag:gson] instead of [tag:json-simple]? – Andreas Mar 05 '20 at 10:09
  • @Himanshi *"what is a better approach"* Not to re-invent the wheel, i.e. don't try to generate correct JSON, when there are so very many nice and free libraries already able to do it for you, which have been tested so they do it right. – Andreas Mar 05 '20 at 10:11
  • @Andreas thanks i'm trying with your suggested way – Himanshi Mar 05 '20 at 10:13

1 Answers1

0

Don't know what you've messed up, since you didn't share the relevant code, but you tagged , so here is how you could generate that JSON output using Gson, and simply defining the data in Maps and Lists.

The code uses Java 9's List.of() and Map.of() to simplify the data building.

List<?> fileContent = List.of(
        Map.of("_fields", Map.of("key1", "value1", "key2", "value2")),
        Map.of("_fields", Map.of("key1", "value1", "key2", "value2")),
        Map.of("_count", 12, "links", List.of(
                Map.of("rel", "prev", "href", "http://localhost:8080/someprevurl"),
                Map.of("rel", "next", "href", "http://localhost:8080/somenexturl"),
                Map.of("rel", "self", "href", "http://localhost:8080/selfurl")
        ))
);

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(fileContent);
System.out.println(json);

Output

[
  {
    "_fields": {
      "key2": "value2",
      "key1": "value1"
    }
  },
  {
    "_fields": {
      "key2": "value2",
      "key1": "value1"
    }
  },
  {
    "_count": 12,
    "links": [
      {
        "href": "http://localhost:8080/someprevurl",
        "rel": "prev"
      },
      {
        "href": "http://localhost:8080/somenexturl",
        "rel": "next"
      },
      {
        "href": "http://localhost:8080/selfurl",
        "rel": "self"
      }
    ]
  }
]
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • @andres I've JSONArray and not list – Himanshi Mar 05 '20 at 10:07
  • @Himanshi This answer is based of the *fact* that you said you're using Gson, and is simply illustrating that you should be doing any "toString" implementations to get the output you need. Whether the input is an array, a `List`, a `JSONArray`, or some other collection that Gson understands, is entirely beside the point. – Andreas Mar 05 '20 at 10:13