How to create POJO class for retrofit with dynamic keys names

600 Views Asked by At

I am sorry but i couldn't even phrase the question well but here it goes. I am getting a JSON response like this:

{
    "results": {
        "b2bc01": [{
            "message": "Successfully created",
            "_id": "596c8b25ce2350e41600002f",
            "status": "Success",
            "code": 200
        }],
        "b2bc02": [{
            "message": "Successfully created",
            "_id": "596c8b25ce2350e416000030",
            "status": "Success",
            "code": 200
        }]
        .
        .
        .
        "b2bc0n":[{
            "message": "Successfully created",
            "_id": "596c8b25ce2350e416000030",
            "status": "Success",
            "code": 200
            }]
    }
}

How do i create POJO class for this type of JSON. I tried in jsonschema2pojo but i feel its not a good result. Please help. Thank in advance

2

There are 2 best solutions below

0
On BEST ANSWER

Your POJO file

class MyPojo {
    HashMap<String, ArrayList<MyModel>> results;

    class MyModel {
        String message;
        String _id;
        String status;
        int code;
    }
0
On

You can only use pojo with this data:

[{
            "message": "Successfully created",
            "_id": "596c8b25ce2350e41600002f",
            "status": "Success",
            "code": 200
        }]

And if you use retrofit 2 and gson, I recommend you use interface JsonDeserializer

with .registerTypeAdapter()

Example

Gson gson = new GsonBuilder()
                            .excludeFieldsWithoutExposeAnnotation()
                            .registerTypeAdapter(GpcProductDetail.class, new GpcProductDeserializer())
                            .create();

And parse manually that part of json.