简体   繁体   English

Java JsonObject数组值为key

[英]Java JsonObject array value to key

I'm new to java so this is a bit confusing 我是java的新手,所以这有点令人困惑

I want to get json formatted string 我想得到json格式的字符串

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")); 我尝试了这个,但它没有工作json.put(“user”,json.put(“name”,“Lamis”));

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. 然而 ,你所展示的“错误”结果将是“有一个名为 ”lamis“的用户比”正确“结果更自然的映射。

Why do you think the "correct" result is better? 为什么你认为“正确”的结果更好?

Another way of doing it is to use a JSONArray for presenting a list 另一种方法是使用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" ] }

Probably what you are after is different than what you think you need; 你所追求的可能与你认为需要的不同;

You should have a separate 'User' object to hold all properties like name, age etc etc. And then that object should have a method giving you the Json representation of the object... 你应该有一个单独的'User'对象来保存所有属性,如名称,年龄等等。然后该对象应该有一个方法给你对象的Json表示...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM