Lamis Lamis - 2 years ago 181
Java Question

Java JsonObject array value to key

I'm new to java so this is a bit confusing

I want to get json formatted string

The result I want is

{ "user": [ "name", "lamis" ] }

What I'm currently doing is this :

JSONObject json = new JSONObject();
json.put("name", "Lamis");

And I'm getting this result


I tried this but it didnt work
json.put("user", json.put("name", "Lamis"));

Answer Source

Try this:

JSONObject json = new JSONObject();         
json.put("user", new JSONArray(new Object[] { "name", "Lamis"} ));

However the "wrong" result you showed would be a more natural mapping of "there's a user with the name "lamis" than the "correct" result.

Why do you think the "correct" result is better?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download