我将Retrofit 2与Gson和RxJava结合使用。我的JSON数据看起来像这样:
{
"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
}
在上面的示例中,"键" 1,2,3是整数,但它们也可以是唯一的字符串。我想将这个JSON数据映射到这样的东西:
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
}
将动态密钥(1,2,3)放入Group
对象的最佳方法是什么?我自己没有托管JSON数据,因此无法将其更改为其他格式。
答案 0 :(得分:3)
步骤A - 创建组类:
public class Group {
String name;
String type;
}
步骤B - 创建群组类:
public class Groups {
List<Group> userList;
}
步骤C - 创建GSON反序列化器类
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;
}
}
步骤D - 在创建Gson对象时注册反序列化器
Gson gson = new GsonBuilder()
.registerTypeAdapter(Groups.class, new MyDeserializer()).create();
步骤E - 转换您的JSON对象。 GSON
Groups groups = gson.fromJson(jsonExmple, Groups.class);
注意: