问题
I'm using Retrofit 2 in combination with Gson and RxJava. My JSON data looks something like this:
{
"groups": {
"1": {
"name": "First group",
"type": "some data",
// ... more data
},
"2": {
"name": "Second group",
"type": "some data",
// ... more data
},
"3": {
"name": "Third group",
"type": "some data",
// ... more data
}
// 4, 5, 6, etc...
},
// ... more data
}
In the example above the "keys" 1, 2, 3 are integers but they can also be unique strings. I want to map this JSON data to something like this:
public class MyData {
@SerializedName("groups")
private Map<String, Group> mGroups;
// ... more data
}
public class Group {
// TODO: This should be "1", "2", "3", etc.
@SerializedName(???)
private String mId;
// This should be "First group", "Second group", "Third group", etc.
@SerializedName("name")
private String mName;
// This should be "some data"
@SerializedName("type")
private String mType;
// ... more data
}
What's the best way to put the dynamic key (1, 2, 3) in the Group
object as well? I'm not hosting the JSON data myself so it cannot be changed to another format.
回答1:
Step A - Create a group class:
public class Group {
String name;
String type;
}
Step B - Create a groups class:
public class Groups {
List<Group> userList;
}
Step C - Create a GSON Deserializer class
public class MyDeserializer implements JsonDeserializer<Groups> {
private final String groups_key = "groups";
@Override
public Groups deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Groups groups = new Groups();
JsonObject object = json.getAsJsonObject().getAsJsonObject(groups_key);
Map<String, Group> retMap = new Gson().fromJson(object, new TypeToken<HashMap<String, Group>>() {}.getType());
List<Group> list = new ArrayList<Group>(retMap.values());
groups.userList = list;
return groups;
}
}
Step D - Register your Deserializer when you create your Gson object
Gson gson = new GsonBuilder()
.registerTypeAdapter(Groups.class, new MyDeserializer()).create();
Step E - Convert your JSON object via. Gson
Groups groups = gson.fromJson(jsonExmple, Groups.class);
Notes:
- When your JSON object gets bigger you can expand your Group/Groups classes and add more variables. Keep in mind that you will need to reflect everything in your Deserializer class. :)
- Use @SerializedName annotation when your variable got a different name from your JSON key
来源:https://stackoverflow.com/questions/45131547/retrofit2-convert-json-with-dynamic-keys-to-a-mapstring-model-with-model-als