3

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"));

Lamis
  • 456
  • 3
  • 9
  • 19

3 Answers3

14

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?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
8

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" ] }
peter
  • 8,333
  • 17
  • 71
  • 94
1

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());
    }
}
lithium
  • 995
  • 7
  • 13