Home > Software design >  Map JSONObject to Java Object
Map JSONObject to Java Object

Time:10-22

I'm developing an Android application that needs to contact an API REST that gives a JSON structured as follow

{
     "TEST1": [
        {
            "delegate": true,
            "unit": "mmHg",
            "code": "DIA",
            "read": true,
            "write": true
        },
        {
            "delegate": true,
            "unit": "mmHg",
            "code": "SYS",
            "read": true,
            "write": true
        }
    ],
    "TEST2": [
        {
            "delegate": true,
            "unit": "°C",
            "code": "TEMPERATURE",
            "read": true,
            "write": true
        }
    ]}

Now I thought to map the inner object in the array as a simple Java Object (e.g MyObject) with 5 fields, but how can I map the entire Object when I do the retrofit call? I don't think that

 List<List<MyObject>>

would fit this case since I need to know the keys ("TEST1", "TEST2"). Any help will be appreciated

CodePudding user response:

Maybe the best choice is to map the response in a JsonObject and then take the values with

JsonArray test1 = jsonObject.getAsJsonArray("TEST1");

you could use a counter based on the response's length to make it more dynamic like:

int testCounter = 0;    
JsonArray test1 = jsonObject.getAsJsonArray("TEST");

inside a loop of course

  • Related