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"}}
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.
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.
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.
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); } }
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