Reputation: 13931
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?
Upvotes: 34
Views: 166469
Reputation: 253
This will do what you want !
JSONObject json = new JSONObject();
json.put("Command", "CreateNewUser");
json.put("User", new JSONObject(user));
Upvotes: 9
Reputation: 1762
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/
Upvotes: 0
Reputation:
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"
}
Upvotes: 60
Reputation: 3512
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()));
Upvotes: 1
Reputation: 4432
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.
Upvotes: 5