如何将对象添加为JsonObject对象的属性? [英] How to add an object as a property of a JsonObject object?

查看:157
本文介绍了如何将对象添加为JsonObject对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在做什么:

JsonObject jobj = new JsonObject();
jobj.addProperty("name", "great car");

我希望添加另一个值为对象的属性,如下所示:

I am hoping to add another property whose value is an object as follows:

jobj.addProperty("car", A_CAR_OBJECT);

但是,看来GSON不允许我执行jobj.addProperty("car", A_CAR_OBJECT).我最终将要执行以下操作:

But it appears that GSON does not allow me to do jobj.addProperty("car", A_CAR_OBJECT). I am going to eventually do the following:

String json = new Gson().toJson(jobj);

获取Json字符串.

这可行吗?我是否以正确的方式使用GSON?还是应该只使用HashMap将所有数据放入其中,然后再放入new Gson().toJson()?

Is this doable? Am I using GSON the right way? Or should I just use a HashMap to throw all data into it and then new Gson().toJson()?

推荐答案

您可以这样做:

jobj.add("car", new Gson().toJsonTree(A_CAR_OBJECT));

这篇关于如何将对象添加为JsonObject对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆