Java 如何正确地将对象放入 JSONObject 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30005939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:58:32  来源:igfitidea点击:

How to put object into JSONObject properly?

javaandroidjson

提问by Kamil

I'm trying to fill my JSONObject like this:

我正在尝试像这样填充我的 JSONObject:

JSONObject json = new JSONObject();
json.put("Command", "CreateNewUser");
json.put("User", user);

useris instance of basic class that contains fields like "FirstName", "LastName" etc.

user是包含“FirstName”、“LastName”等字段的基本类的实例。

Looks like I'm doing it wrong, because I get JSON like this:

看起来我做错了,因为我得到这样的 JSON:

{
    "Command":"CreateNewUser",
    "User":"my.package.name.classes.User@2686a150"
}

instead of "tree".

而不是“树”。

What is wrong with my code?

我的代码有什么问题?

采纳答案by Francesco Menzani

Since you use JSONObjectto represent non-primitive types, any instance passed to JSONObject.put(Object, Object)will generate nested items (or trees).

由于您用于JSONObject表示非原始类型,因此传递给的任何实例都JSONObject.put(Object, Object)将生成嵌套项(或)。

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

回答by Rafal G.

The framework you are using does not know how to convert your User object to a Map, that is used internally as JSON representation and so it is using standard 'toString' method that you have not overriden.

您使用的框架不知道如何将您的 User 对象转换为 Map,它在内部用作 JSON 表示,因此它使用您尚未覆盖的标准“toString”方法。

Just export all properties (for example write method 'Map toMap()' on your User type ) of your User to a Map (all values must be standard JDK types) and put that map in your json object:

只需将您的 User 的所有属性(例如在您的 User 类型上写入方法 'Map toMap()' )导出到 Map(所有值都必须是标准 JDK 类型)并将该映射放入您的 json 对象中:

json.put("User", user.toMap())

It will do the thing.

它会做这件事。

回答by user2829759

From http://developer.android.com/reference/org/json/JSONObject.html#put

来自http://developer.android.com/reference/org/json/JSONObject.html#put

 public JSONObject put (String name, Object value)

Parameters value a JSONObject, JSONArray, String, Boolean, Integer, Long, Double, NULL, or null. May not be NaNs or infinities.

参数值为 JSONObject、JSONArray、String、Boolean、Integer、Long、Double、NULL 或 null。可能不是 NaN 或无穷大。

Though your useris subclass of Object, it is not the type that the putmethod expects.

尽管您user是 的子类Object,但它不是该put方法期望的类型。

The android SDK's implementation of JSONObjectseems lacking a put(java.lang.String key, java.util.Map value)method (from the same link above). You may need to add a method toMap()in your userclass to convert it into a HashMap. Then finally use json.put("user", new JSONObject(user.toMap()));

android SDK 的实现JSONObject似乎缺少put(java.lang.String key, java.util.Map value)方法(来自上面的同一链接)。您可能需要toMap()user类中添加一个方法以将其转换为HashMap. 然后最后使用json.put("user", new JSONObject(user.toMap()));

回答by Kevindra

You can solve it using fasterxml ObjectMapper.

您可以使用 fastxml ObjectMapper 解决它。

ObjectMapper o = new ObjectMapper();
String userJsonString = o.readValueAsString(user);

JSONObject jsonObj = new JSONObject();
jsonObj.put("Command", "CreateNewUser");
jsonObj.put("User", new JSONObject(userJsonString));

You will get following output:

您将获得以下输出:

{
    "User": {
        "FirstName": "John",
        "LastName": "Reese"
    },
    "Command": "CreateNewUser"
}

Ref: https://github.com/FasterXML/Hymanson-databind/

参考:https: //github.com/FasterXML/Hymanson-databind/

回答by Hrant Vardanyan

This will do what you want !

这会做你想做的!

JSONObject json = new JSONObject();
json.put("Command", "CreateNewUser");
json.put("User", new JSONObject(user));