开发者

Creating GSON Object

How do I create a json Object using Google Gson? The following code creates a json开发者_StackOverflow社区 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"}}


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 HashMap<String, String> publisher = new HashMap<String, String>();

    public Creator(String name){
            publisher.put("name", name);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜