2015-04-17 43 views
9

在服務器端的名單序列化映射到/我得到這個API(例如)GSON串行/從KeyValuePairs

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; 
} 

它更具有像複雜的密鑰對象intresting:

class ComplexKey { 
    @SerializedName("Key1") 
    private int key1; 

    @SerializedName("Key2") 
    private String key2; 
} 

class GetMyObject { 
    @SerializedName("MyDictionary") 
    private Map<ComplexKey, Integer> myDictionary; 
} 

回答

8

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()); 
+1

我怎樣才能使通用的,所以我沒有創建每個地圖? –

+0

@GergelyFehérvári我已經編輯了我的答案一次。我剛剛嘗試了這種方法,它只是用泛型來尋找。 –

1

替代,傑克遜JSON處理器

@JsonDeserialize(contentAs=Integer.class) 
private Map<ComplexKey, Integer> myDictionary;