2

我想要这个结果:

{"link":[{"url":"http://en.wikipedia.org/wiki/JScript", "label":"wikipedia"}]}

我试过这个:

JSONObject ob1 = new JSONObject();
ob1.put("link","[{\"url\":\"http://en.wikipedia.org/wiki/JavaScript\", label:\"wikipedia\"}]");

ob1.toJSONString() 的输出是:

{"link":"[{\"url\":\"http:\/\/en.wikipedia.org\/wiki\/JavaScript\", label:\"wikipedia\"}]"}

我做错了什么?我正在使用 json-simple-1.1.1

4

1 回答 1

0

You should put a JSONArray into the JSONObject and in the Array again a JSONObject with the keys/values "url"/"http://en.wikipedia.org/wiki/JScript" and "label"/"wikipedia"

JSONObject ob1 = new JSONObject();
JSONArray ar1 = new JSONArray();
ob1.put ("link", ar1);

JSONObject ob2 = new JSONObject();
ar1.add(ob2);

ob2.put("url", "http://en.wikipedia.org/wiki/JScript");
ob2.put("label", "wikipedia");

In case you have the value of ob1 link object already as JSON string then you can first interpret this into a JSONArray using

JSONArray ar1 = (JSONArray)JSONValue.parse(yourJSONStr);

NOTE: Your intended result is not a JSON string, because for that all "/" must be escaped "\/"

于 2013-07-25T09:09:25.863 回答