Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put object into JSONObject properly?

Tags:

java

json

android

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?

like image 404
Kamil Avatar asked May 02 '15 18:05

Kamil


People also ask

How do you initiate a JSON object?

String message; JSONObject json = new JSONObject(); json. put("test1", "value1"); JSONObject jsonObj = new JSONObject(); jsonObj. put("id", 0); jsonObj.

How do I write a JSON object file?

UseJSON. stringify(jsonObject) to convert JSON Object to JSON String. Write the stringified object to file using fs. writeFile() function of Node FS module.


1 Answers

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" } 
like image 107
Atom 12 Avatar answered Oct 13 '22 09:10

Atom 12