Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating GSON Object

Tags:

java

json

gson

How do I create a json Object using Google Gson? The following code creates a json object which looks like {"name":"john"}

JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("name", "john"); 

How do I create a jSon Object like this one?

{"publisher":{"name":"john"}} 
like image 765
Raunak Avatar asked Jan 13 '11 18:01

Raunak


People also ask

What is a Gson object?

Gson is a Java library that can be used to convert Java objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including objects for which you do not have the source.

What does Gson to JSON do?

Gson (by Google) is a Java library that can be used to convert a Java object into JSON string. Also, it can used to convert the JSON string into equivalent java object.


2 Answers

JsonObject innerObject = new JsonObject(); innerObject.addProperty("name", "john");  JsonObject jsonObject = new JsonObject(); jsonObject.add("publisher", innerObject); 

http://www.javadoc.io/doc/com.google.code.gson/gson


Just an FYI: Gson is really made for converting Java objects to/from JSON. If this is the main way you're using Gson, I think you're missing the point.

like image 70
Matt Ball Avatar answered Sep 20 '22 16:09

Matt Ball


Figured it out how to do it correctly using Java Objects.

Creator creator = new Creator("John"); new Gson().toJson(creator); 

Implementation of Creator java class.

public class Creator {      protected String name;      protected HashMap<String, String> publisher = new HashMap<String, String>();      public Creator(String name){             publisher.put("name", name);     } } 
like image 40
Raunak Avatar answered Sep 24 '22 16:09

Raunak