user82302124
user82302124

Reputation: 1143

Using GSON with object to print JSON object

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

Upvotes: 6

Views: 23118

Answers (2)

Gugelhupf
Gugelhupf

Reputation: 970

Try this :

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonStr = gson.toJson(YourObject);

Upvotes: 0

Jesse Wilson
Jesse Wilson

Reputation: 40623

Replace this:

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

with this:

String json = gson.toJson(p);

Upvotes: 12

Related Questions