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