My code to create a new JSONObject and write to a file:
JSONObject obj = new JSONObject();
obj.put(\"name\", \"abcd\");
obj.put(\"age\", new Integer(100));
J
Simply stringifying the JsonObject will not work. Using json-simple 3.1.0, JsonObject.toString()
will not write the object as valid JSON.
Given the JSON Object as:
JsonObject my_obj = new JsonObject();
my_obj.put("a", 1);
my_obj.put("b", "z");
my_obj.put("c", true);
file.write(my_obj.toString());
Will save as
{a=1, b=z, c=true}
Which is not valid JSON.
To fix this, you need to use the Jsoner
.
Working Example
import com.github.cliftonlabs.json_simple.JsonObject;
import com.github.cliftonlabs.json_simple.Jsoner;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Example {
public static void main(String args[]) {
JsonObject my_obj = new JsonObject();
my_obj.put("a", 1);
my_obj.put("b", "z");
my_obj.put("c", true);
try {
BufferedWriter writer = Files.newBufferedWriter(Paths.get("test.json"));
Jsoner.serialize(my_obj, writer);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Which saves as
{"a":1,"b":"z","c":true}
Which is valid JSON.
The method toJSONString()
is from json-simple
but I guess you are using org.json
.
org.json
have an alternative to toJSONString()
.
You can simply use: obj.toString(1)
.
The difference to the toString()
method is, that if you pass "1" as parameter org.json
automatically will format and beautify your JSON
.
So you don't have only one single compressed line of JSON
in your file.
I meet the same question, if you want to use toJSONString()
you need to import json-simple-1.1.jar
library.
The JSONObject class doesn't have a toJSONString()
method. Instead it overrides the toString() method to generate json.
To get the json representation of the object, simply use obj.toString()
.