user3677365
user3677365

Reputation: 95

How to Parse JSON with dynamic Keyname?

I have a JSON response like this.

{
"array": [
    {
        "object1": {
            "aa": "somevalue1",
            "bb": "somevalue2",
            "cc": "somevalue3"
        }
    },
    {
        "object2": {
            "aa": "somevalue4",
            "bb": "somevalue5",
            "cc": "somevalue6"
        }
    }
]}

Now I can get a JSON array from above response. I want read the value aa,bb,cc from object object1 and object2 in a for loop.

JSON is dynamic, I mean that object2 can also appear before object1 (in reverse order) and there is chances that I might get one more object(object3) with same structure OR only one (object1 or object2 or object3).

I dont want to do like this as I failed in :

JSONArray jsonArray = json.getJSONArray("array");
for (int i = 0; i < jsonArray.length(); i++) 
{
    JSONObject jsonObject = jsonArray.getJSONObject(i).getJSONObject("object1");
}

So my question is HOW can I read those values aa,bb,cc without depending on object name or number of object (object1 or object2 or object3)?

Upvotes: 2

Views: 3805

Answers (3)

nndru
nndru

Reputation: 2107

I think you should have next Java-side structure of classes:

  1. Entity - class that will hold aa, bb and cc fields

  2. Container - a class that will consist of two fields - Name and Entity, where Name can store object1, object2 or whatever.

Then, you should deserialize provided JSON into collection/array of Container entities.

Hope this helps.

Update: please check this example Collection deserialization

Upvotes: 1

Andr&#233;s Oviedo
Andr&#233;s Oviedo

Reputation: 1428

You should work with dynamic structures like java.util.Map. Try with this:

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

public class JsonTest {

    public static void main(String[] args) {
        String json = "{\"array\": [{\"object1\": {\"aa\": \"somevalue1\",\"bb\": \"somevalue2\",\"cc\": \"somevalue3\"}},{\"object2\": {\"aa\": \"somevalue4\",\"bb\": \"somevalue5\",\"cc\": \"somevalue6\"}}]}";
        System.out.println(json);
        final MyJson parseJsonSpecification = parseJsonSpecification(json);
        System.out.println(parseJsonSpecification.array.get(0).get("object1"));
        System.out.println(parseJsonSpecification);
    }

    public static MyJson parseJsonSpecification(String jsonString) {
        try {
            if (StringUtils.isBlank(jsonString)) {
                return new MyJson();
            }
            MyJson ret;
            ret = new ObjectMapper().readValue(jsonString, new TypeReference<MyJson>() {
            });
            return ret;
        } catch (Exception ex) {
            throw new IllegalArgumentException("La expresión '" + jsonString + "' no es un JSON válido", ex);
        }
    }
}

class MyJson {
    public List<Map<String, Object>> array;
}

Upvotes: 0

Gil Moshayof
Gil Moshayof

Reputation: 16771

It looks like each item in the array only has 1 key/value pair which holds another json object which then has several.

If this is the case, then you could probably do something like this:

for (int i = 0; i < jsonArray.length(); i++)
{
    JSONObject jsonObject = jsonArray.getJSONObject(i);

    JSONObject innerObject = jsonObject.getJSONObject(jsonObject.keys().next().toString());

    /// do something with innerObject which holds aa, bb, cc
}

You simply grab the 1st key in the wrapping object, and use that to grab the inner json object.

Upvotes: 1

Related Questions