0

I have a JSON file that is stored in the DB after parsing it using JAVA functions. The JSON has an attribute that has multiple lines and should be well formatted. Right now, I am using \n & \t to format this string. Is there a better way to format this string in the JSON? I could use any markup language if available.

"Actions": "Actions required: \n1. Action 1 \n2. Action 2 \n \n Other Actions \n1. Action3 \n2. Action 4

  • This shoud help https://stackoverflow.com/questions/14515994/convert-json-string-to-pretty-print-json-output-using-jackson – F. Vorontsov Nov 22 '21 at 16:24
  • Thanks for sharing this post. But the attribute in the post you share is not a string, it is an array of objects. Would mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); work over a string as in my case? – Apurva Sawant Nov 22 '21 at 20:36

1 Answers1

0

There are a few JSON solutions for Java. I have used JSON-simple and GSON. I think GSON is better because JSON-simple has not been updated in quite some time. Here's the Maven repo for GSON https://mvnrepository.com/artifact/com.google.code.gson/gson

If you need to read an JSON-formatted file, you will do something like this:

Gson gsonObj = new Gson();
YourClass yourObj = new YourClass();

Once you have the GSON object, if the object that your are serializing/deserializing is a ParameterizedType (i.e. contains at least one type parameter and may be an array) then you must use the toJson(Object, Type) or fromJson(String, Type). In your case, you need to convert to a String (to JSON).

String json = gsonObj.toJson(yourObj, new FileWriter("C:\\myjsonfile.json"));

BUT, if your object is simple, you can simply do the following.

String json = gsonObj.toJson(youObj);
hfontanez
  • 5,774
  • 2
  • 25
  • 37
  • Thanks for your detailed input. In my scenario, the YourClass has 'actions' attribute with data type String. This string could be an ordered list, an unordered list, or just one sentence. if it is an ordered list like the one specified below. How can I manage the formatting without using newline characters? Example: - "Actions": "Actions required: 1. Action 1 2. Action 2 Other Actions 1. Action3 2. Action 4 ". – Apurva Sawant Nov 22 '21 at 20:49
  • @ApurvaSawant `YourClass` will need to override the `Object#toString()` method to format the outputted string however you will need it to look like. – hfontanez Nov 23 '21 at 15:44
  • 1
    Got it. Thanks a lot for your help :) – Apurva Sawant Nov 24 '21 at 18:37