Using GSON with object to print JSON object

gson, java, json

Solution

Replace this:

gson.toJson(p);
String json = gson.toString();

with this:

String json = gson.toJson(p);

Problem

Quick questions about GSON, after reading the documentation. This is what I have with JSON: ``` var json = { id: "person1", name: "person 1", data: {"email": "1@test.com"}, children: [{ id: "person2", name: "person 2", data: {"email": "2@test.com"}, children: [] },{ id: "person3", name: "person 3", data: {"email": "3@test.com"}, 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

Original source