在服务器端我得到了这个 API(示例)(我不能修改它。)
namespace MyNameSpace
{
[Serializable][DataContract]
public class GetMyObject
{
[DataMember]
public Dictionary<int, int> MyDictionary { get; set; }
}
}
然后服务器发送这个 JSON:
{
"MyDictionary" :
[{
"Key" : 1,
"Value" : 1
},
{
"Key" : 2,
"Value" : 2
},
{
"Key" : 3,
"Value" : 3
},
{
"Key" : 4,
"Value" : 4
}]
}
在客户端,我必须创建这些类以进行正确的反序列化:
class GetMyObject {
@SerializedName("MyDictionary")
private List<MyDictionaryItem> myDictionary;
}
class MyDictionaryItem {
@SerializedName("Key")
private int key;
@SerializedName("Value")
private int value;
}
我如何配置 GSON 以简单地使用它:(序列化和反序列化)
class GetMyObject {
@SerializedName("MyDictionary")
private Map<Integer, Integer> myDictionary;
}
它对复杂的关键对象更加有趣,例如:
class ComplexKey {
@SerializedName("Key1")
private int key1;
@SerializedName("Key2")
private String key2;
}
class GetMyObject {
@SerializedName("MyDictionary")
private Map<ComplexKey, Integer> myDictionary;
}
最佳答案
创建自定义 JsonDeserializer
对于 Map<?, ?>
:
public class MyDictionaryConverter implements JsonDeserializer<Map<?, ?>> {
public Map<Object, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
Type[] keyAndValueTypes = $Gson$Types.getMapKeyAndValueTypes(typeOfT, $Gson$Types.getRawType(typeOfT));
Map<Object, Object> vals = new HashMap<Object, Object>();
for (JsonElement item : json.getAsJsonArray()) {
Object key = ctx.deserialize(item.getAsJsonObject().get("Key"), keyAndValueTypes[0]);
Object value = ctx.deserialize(item.getAsJsonObject().get("Value"), keyAndValueTypes[1]);
vals.put(key, value);
}
return vals;
}
}
并注册它:
gsonBuilder.registerTypeAdapter(new TypeToken<Map>(){}.getType(),
new MyDictionaryConverter());
关于java - Gson 序列化/反序列化映射到/从 KeyValuePairs 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29695738/