简体   繁体   中英

Android: deserialize dynamic JSON with Retrofit and Jackson

I need to deserialize a dynamic JSON with unknown name of properties and I can't get it done.

The JSON looks like this:

{ Player: [ { name: "name", surname: "surname", email: "email", photo: "photo", position: "position" } ], ... } So basically, this would be a JSON object containing multiple arrays.

The name of the name of the JSON array -Player- is dynamic, and I have just included the first array, but in the JSON object there can be multiple arrays. Otherwise, if the wasn't dynamic, then I would include it in the declaration of the fields of the model with @JsonProperty.

Thanks a lot in advance.

What I did here was creating my own deserializer and using it when creating the Gson:

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

And here's the deserializer:

public class MyJsonDeserializer implements JsonDeserializer<MyModel> {
@Override
public MyModel deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    Gson gson = new GsonBuilder().create();
    MyModel myModel = new MyModel();
    Iterator it = ((JsonObject) json).entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        if (entry.getValue() instanceof JsonArray) {
            JsonArray myModelJsonArray = (JsonArray) entry.getValue();
            MyModel2 mymodel2 = new MyModel2();
            if (entry.getKey() instanceof String) {
                mymodel2.setName((String) entry.getKey());
            }
            for (int i = 0; i < myModelJsonArray.size(); i++) {
                JsonElement jsonElementMember = myModelJsonArray.get(i);
                mymodel2.getMembers().add(gson.fromJson(jsonElementMember, Member.class));
            }
            myModel.getMyModel2().add(myModel2);
        }
    }
    return myModel;
}

}

It is basically creating the structure of the JSON manually, with all its hierarchies.

Thanks a lot for your help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM