2

I want this outcome:

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

I tried this:

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

The output of ob1.toJSONString() is:

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

What am I doing wrongly? I am using json-simple-1.1.1

Ankur Lathi
  • 7,636
  • 5
  • 37
  • 49
Jean
  • 1,480
  • 15
  • 27

1 Answers1

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 "\/"

luksch
  • 11,497
  • 6
  • 38
  • 53
  • Ah that was dumb of me. the problem with the url still exists. I am getting the following and I can't escape the / with \/. {"link":[{"url":"http:\/\/en.wikipedia.org\/wiki\/JavaScript","label":"wikipedia"}]} – Jean Jul 25 '13 at 09:23
  • That is JSON spec. Your string would not be a correct JSON formatted string. – luksch Jul 25 '13 at 09:27
  • so it is not possible to get my desired outcome? – Jean Jul 25 '13 at 09:28
  • I don't think so, because json-simple is following the JSON specification. – luksch Jul 25 '13 at 09:30