Java JsonObject array value to key

前端 未结 3 1500
有刺的猬
有刺的猬 2021-01-03 09:53

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


        
相关标签:
3条回答
  • 2021-01-03 10:44

    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...

    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());
        }
    }
    
    0 讨论(0)
  • 2021-01-03 10:50

    Another way of doing it is to use a JSONArray for presenting a 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" ] }
    
    0 讨论(0)
  • 2021-01-03 10:53

    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?

    0 讨论(0)
提交回复
热议问题