Creating GSON Object

JavaJsonGson

Java Problem Overview


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"}}

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRaunakView Question on Stackoverflow
Solution 1 - JavaMatt BallView Answer on Stackoverflow
Solution 2 - JavaRaunakView Answer on Stackoverflow