[英]Gson serialize/deserialize Map to/from list of KeyValuePairs
在服務器端,我得到了這個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;
}
為Map<?, ?>
創建自定義JsonDeserializer
:
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());
另一種是Jackson JSON處理器
@JsonDeserialize(contentAs=Integer.class)
private Map<ComplexKey, Integer> myDictionary;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.