views:

196

answers:

3

Hi all,

I want to genrate following JSON dataobject using org.json.simple.JSONObject, how to do it in java?

{
  friends : [
    {
      name: 'David',
      interests: 'Cooking',
    },
    {
      name: 'Charles',
      interests: 'Hiking',
    },
    {
      name: 'Mary',
      interests: 'Football',
    },
  ]
}

If code snipet is provided then that will be really helpful!

Regards, Abhi

+1  A: 
    JSONArray arr = new JSONArray();

    JSONObject entry = new JSONObject();
    entry.put("key1", "value1");
    entry.put("key2", "value2");

    arr.add(entry);

    JSONObject json = new JSONObject();
    json.put("friends", arr);

    System.out.println(json.toJSONString());

output:

{"friends":[{"key2":"value2","key1":"value1"}]}
Frostman
Hi, thanks for quick responce! I have one more query, cant we remove quotes from from keys for ex: key: 'value'
Abhishek
+1  A: 

I know only one way to delete quotes:

public class Test {
public static void main(String[] args) {
    JSONArray users = new JSONArray();
    users.add(new Entry("key1", "val1"));
    users.add(new Entry("key2", "val2"));        

    System.out.println(users);
}

static class Entry implements JSONAware {
    private String name;
    private String interests;

    public Entry(String name, String interests) {
        this.name = name;
        this.interests = interests;
    }

    public String toJSONString() {
        StringBuffer sb = new StringBuffer();

        sb.append("{");

        sb.append(JSONObject.escape("name"));
        sb.append(":");
        sb.append("\"" + JSONObject.escape(name) + "\"");

        sb.append(",");

        sb.append(JSONObject.escape("interests"));
        sb.append(":");
        sb.append("\"" + JSONObject.escape(name) + "\"");

        sb.append("}");

        return sb.toString();
    }
}

}

output:

[{name:"key1",interests:"key1"},{name:"key2",interests:"key2"}]
Frostman