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
CodePudding user response:
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);