Gson序列化/反序列化Map到/从KeyValuePairs列表

时间:2015-04-17 09:43:48

标签: java json dictionary gson

在服务器端,我得到了这个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;
}

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:1)

另一种是杰克逊JSON处理器

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