0

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

ewernli
  • 38,045
  • 5
  • 92
  • 123
Abhishek Dhote
  • 1,638
  • 10
  • 41
  • 62
  • Any chance to use Gson? Then you can just use `List` without hassling with JSON specifics. – BalusC Mar 15 '10 at 19:12
  • Can you elaborate please? If have an example then it will be really nice as I m new to Gson, but I know you BalusC how r u? – Abhishek Dhote Mar 15 '10 at 19:20
  • Fine, thanks :) Start here for examples: http://stackoverflow.com/questions/2413636/communication-between-jsp-and-servlet/2413767#2413767 – BalusC Mar 15 '10 at 19:51

3 Answers3

1
    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
  • 462
  • 4
  • 11
1

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
  • 462
  • 4
  • 11
0

Please refer here fore removing quotes-

http://helpdesk.objects.com.au/gwt/how-do-i-remove-the-quotes-from-json-strings-returned-to-my-gwt-application

jagamot
  • 5,348
  • 18
  • 59
  • 96