Angelina
Angelina

Reputation: 1573

Use Gson/Retrofit on SerializedName which is unknown beforehand

I need to get data from a badly designed web API which returns the list of objects in the form of JSON object:

    {
       "29593": { ..object to parse },
       "29594": { ..object to parse },
       "29600": { ..object to parse }
    }

I need to create POJO for this response, but the issue is that these integers are changing, they are like object IDs. I don't know how to extract these integers from the JSON keys and then use the inner JSON objects further in another POJO class (I know basic Gson mapping when the key has a fixed value).

Is it even possible?

Upvotes: 1

Views: 1301

Answers (1)

Link182
Link182

Reputation: 839

The solution is to use a custom JsonDeserializer from gson library, here is a example:

public class MyAwesomeDeserializer implements JsonDeserializer<MyModel> {
    public MyModel deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject eJson = json.getAsJsonObject();
        Set<String> keys = eJson.keySet();
        MyModel myModel = new MyModel();
        for (String key: keys) {
            JsonObject asJsonObject = eJson.get(key).getAsJsonObject();
            ItemOfMyModel itemOfMyModel = context.deserialize(asJsonObject, ItemOfMyModel.class);
            myModel.addItemOfMyModel(itemOfMyModel);
        }
        return myModel;
    }
}

and dont forget to add your custom deserializer as a type adapter to gson builder:

Gson gson = new GsonBuilder()
            .registerTypeAdapter(MyModel.class, new MyAwesomeDeserializer())
            .create()

Upvotes: 1

Related Questions