Java JsonObject array value for key

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

I want to get json formatted string

As a result i want

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

I am currently doing the following:

 JSONObject json = new JSONObject(); json.put("name", "Lamis"); System.out.println(json.toString()); 

And I get this result

 {"name":"Lamis"} 

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

+3
source share
3 answers

Try the following:

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

However, the result “wrong” that you showed will be a more natural display of “there is a user named“ lamis ”than the“ correct ”result.

Why do you think the best result?

+11
source

Another way to do this is to use JSONArray to represent the list

  JSONArray arr = new JSONArray(); arr.put("name"); arr.put("lamis"); JSONObject json = new JSONObject(); json.put("user", arr); System.out.println(json); //{ "user": [ "name", "lamis" ] } 
+7
source

Probably what you need is different from what you think is necessary;

You must have a separate User object to store all properties, such as name, age, etc. And then this object should have a method providing you with a Json representation of the object ...

You can check the code below:

 import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; public class User { String name; Integer age; public User(String name, Integer age) { this.name = name; this.age = age; } public JSONObject toJson() { try { JSONObject json = new JSONObject(); json.put("name", name); json.put("age", age); return json; } catch (JSONException e) { e.printStackTrace(); return null; } } public static void main(String[] args) { User lamis = new User("lamis", 23); System.out.println(lamis.toJson()); } } 
+1
source

Source: https://habr.com/ru/post/952938/


All Articles