PaulG
PaulG

Reputation: 506

Inserting JSON Subobject into existing JSON

I get JSON back from a web service call that looks like this:

{
  results : 
    {
     seg: {
        segName: whatever,
        segType: atest,
        var: [
            {field1: value1,
             field2: value2,
             field3: value3},
            {field1: value4,
             field2: value5,
             field3: value6}
            ]
          }
     }
}

I am using the net.sf.json package in Java. I create a JSON object from this result.

I would like to manually add another entry (JSONObject) to the array "var".

Other than deconstructing the object all the way down to the JSONArray "var", and then rebuilding it, is there a way to just insert another entry into var?

I tried accumulate("var", new JSONObject(...)); but that stuck the new object at the same level as "seg" in the "results" section.

Upvotes: 2

Views: 3214

Answers (1)

azurefrog
azurefrog

Reputation: 10945

You have to call accumulate at the level you want the new object inserted.

If you drill down to the "seg" level, and accumulate the new object there, you'll add the new entry to the "var" array.

e.g.

String json = // your input JSON string here
JSONObject obj = new JSONObject(json);
obj.getJSONObject("results")
   .getJSONObject("seg")
   .accumulate("var", new JSONObject("{field1 : value7, field2: value8, field3: value9}"));
System.out.println(obj);

gives

{"results":{"seg":{"var":[{"field3":"value3","field2":"value2","field1":"value1"},{"field3":"value6","field2":"value5","field1":"value4"},{"field3":"value9","field2":"value8","field1":"value7"}],"segType":"atest","segName":"whatever"}}}

Upvotes: 2

Related Questions