Java JsonObject数组值为key

我是java的新手,所以这有点令人困惑

我想得到json格式的字符串

我想要的结果是

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

我目前正在做的是:

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

而且我得到了这个结果

 {"name":"Lamis"} 

我尝试了这个,但它没有工作json.put(“user”,json.put(“name”,“Lamis”));

尝试这个:

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

然而 ,您显示的“错误”结果将是“具有名称 ”lamis“的用户比”正确“结果更自然的映射。

为什么你认为“正确”的结果更好?

另一种方法是使用JSONArray来呈现列表

  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" ] } 

你所追求的可能与你认为的需要不同;

您应该有一个单独的“用户”对象来保存所有属性,如名称,年龄等等。然后该对象应该有一个方法,为您提供对象的Json表示…

你可以查看下面的代码;

 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()); } }