我想使用org.json.simple.JSONObject生成以下JSON数据对象,如何在java中执行此操作?

时间:2010-03-15 18:53:23

标签: java json

我想使用org.json.simple.JSONObject生成以下JSON数据对象,如何在java中执行此操作?

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

提供了代码片段,这将非常有用!

此致 ABHI

3 个答案:

答案 0 :(得分: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());

输出:

{"friends":[{"key2":"value2","key1":"value1"}]}

答案 1 :(得分:1)

我只知道一种删除引号的方法:

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

}

输出:

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

答案 2 :(得分:0)