Gson deserialize Map serialized by WCF Rest ser

2019-05-21 14:22发布

问题:

I have a WCF Rest Service. I would like to use it from Android device. To do this I have chosen gson library. Everything seemed to work fine until I wanted to return from my service Object Containing Map. Gson serializes it (and as I am assuming also tries to deserialize from it) as something like:

{"org.Mob.ComplexObject@3dac2f9c":"TAX1","org.Mob.ComplexObject@7369ca65":"TAX2"}

But the json sent by my service looks like:

{"Key":
    {"DefaultValue":"True",
     "Description":null,
     "DisplayName":"Custom Boolean",
     "FieldType":0,
     "Id":6,
     "IsReadOnly":false,
     "IsRequired":false,
     "MaxLength":null,
     "Name":"BoolVal",
     "ParamType":0},
 "Value":"True"},
{"Key":
    {"DefaultValue":"",
     "Description":null,
     "DisplayName":"Custom Text",
     "FieldType":4,
     "Id":7,
     "IsReadOnly":false,
     "IsRequired":true,
     "MaxLength":16,
     "Name":"TextVal",
     "ParamType":0},
 "Value":"sda"}
}

回答1:

Gson does not have a built-in feature to serialize a Java map into JSON formatted as desired. (The feature to handle complex map keys does not address this.) Custom serialization/deserialization processing is necessary.



回答2:

The other way to do it could be adding you own implementation of Map / Dictionary which extends ArrayList, and in fact is a List of KVPair, where KVPair looks like:

class KVPair<K,V>{
    K Key;
    V Value;
}

I don't know if it's elegant, but it worked in my case.



标签: map gson