Quick questions about GSON, after reading the documentation. This is what I have with JSON:
var json = {
id: "person1",
name: "person 1",
data: {"email": "[email protected]"},
children: [{
id: "person2",
name: "person 2",
data: {"email": "[email protected]"},
children: []
},{
id: "person3",
name: "person 3",
data: {"email": "[email protected]"},
children: []
}
]
}
1) Can I use GSON without using Class objects in Java? Can this be done easily using GSON and Java. Meaning I can do something like
GSON gson = new GSON();
gson.toJson("name", "person 1");
2) When I use this example:
Gson gson = new Gson();
Person p = new Contact(rs.getString("name"));
gson.toJson(p);
String json = gson.toString();
System.out.println(json);
My Json output is not what I expected. That Person instance is a public class instance with just one property - name (for testing purposes). Why would I see essentially Factory, serializeNulls, etc in the output?
Thanks
By default, Gson can print the JSON in compact format. To enable Gson pretty print, we must configure the Gson instance using the setPrettyPrinting() method of GsonBuilder class and this method configures Gson to output JSON that fits in a page for pretty printing.
We can pretty-print a JSON using the toString(int indentFactor) method of org. json. JSONObject class, where indentFactor is the number of spaces to add to each level of indentation.
Reading and writing JSON using GSON is very easy. You can use these two methods: toJSON() : It will convert simple pojo object to JSON string. FromJSON() : It will convert JSON string to pojo object.
Replace this:
gson.toJson(p);
String json = gson.toString();
with this:
String json = gson.toJson(p);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With