我想使用org.json.simple.JSONObject生成以下JSON数据对象,如何在Java中做到这一点?

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

提供的代码段将非常有帮助!
问候,
阿比

最佳答案

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

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

10-07 15:45