Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using GSON with object to print JSON object

Tags:

java

json

gson

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

like image 842
user82302124 Avatar asked May 30 '12 19:05

user82302124


People also ask

How do I print a Gson object?

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.

Can we print JSON object in Java?

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.

How does Gson read JSON?

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.


1 Answers

Replace this:

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

with this:

String json = gson.toJson(p);
like image 181
Jesse Wilson Avatar answered Sep 25 '22 02:09

Jesse Wilson