简体   繁体   中英

How to put object into JSONObject properly?

I'm trying to fill my JSONObject like this:

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

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

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

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

instead of "tree".

What is wrong with my code?

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

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.

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:

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

It will do the thing.

This will do what you want !

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

From 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.

Though your user is subclass of Object , it is not the type that the put method expects.

The android SDK's implementation of JSONObject seems 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 user class to convert it into a HashMap . Then finally use json.put("user", new JSONObject(user.toMap()));

You can solve it using fasterxml 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/jackson-databind/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM