Lamis Lamis - 6 months ago 31
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");
System.out.println(json.toString());


And I'm getting this result

{"name":"Lamis"}


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

Answer

Try this:

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

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?