如何正确地将对象放入JSONObject? [英] How to put object into JSONObject properly?
本文介绍了如何正确地将对象放入JSONObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图像这样填充我的JSONObject:
I'm trying to fill my JSONObject like this:
JSONObject json = new JSONObject();
json.put("Command", "CreateNewUser");
json.put("User", user);
user
是基本类的实例,其中包含诸如名字",姓氏"等字段.
user
is instance of basic class that contains fields like "FirstName", "LastName" etc.
看起来我做错了,因为我得到了这样的JSON:
Looks like I'm doing it wrong, because I get JSON like this:
{
"Command":"CreateNewUser",
"User":"my.package.name.classes.User@2686a150"
}
而不是"tree".
instead of "tree".
我的代码有什么问题?
推荐答案
由于使用JSONObject
表示非原始类型,因此传递给JSONObject.put(Object, Object)
的任何实例都将生成嵌套项(或树 >).
Since you use JSONObject
to represent non-primitive types, any instance passed to JSONObject.put(Object, Object)
will generate nested items (or trees).
JSONObject main = new JSONObject();
main.put("Command", "CreateNewUser");
JSONObject user = new JSONObject();
user.put("FirstName", "John");
user.put("LastName", "Reese");
main.put("User", user);
{
"User": {
"FirstName": "John",
"LastName": "Reese"
},
"Command": "CreateNewUser"
}
这篇关于如何正确地将对象放入JSONObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文