问题
I'm trying to map GeoJSON to DataContracts for use in some WCF-services at work. GeoJSON has a field called "type" and the DataContracts-serialization depends on the field "__type" to support de/serializing to the correct subtypes. My DataContracts are all named after the GeoJSON spec and I've set the Namespace of the DataContracts to "", so basically I have managed to implement GeoJSON <==> DataContracts if only i could tell the (de)serializer to use the field "type" instead of the field "__type".
Is it at all possible to tell WCF or the DataContract serializers what field to look at for type information? How would one go about to support a JSON-standard that actually uses the __type-field?
回答1:
You can't. __type is hardcoded in at the most basic level in DataContractJsonSerializer.
One option you potentially have is to wrap this around ANOTHER serializer, a data contract resolver, or a data contract surrogate, to map whatever is in __type to type (on serialization) and to transfer whatever is in type to __type (on deserialization). This is extra manual work that is quite the headache.
Another option you have is to write your own serializer. This is not as hard to do as you might think, if you just take a look at how DataContractJsonSerializer via Reflector, and mimic it with your writer and reader, and also analyze where DataContractJsonSerializer is used or instantiated.
A third option you have is to to just perhaps another serializer altogether, like JSON .NET
A fourth option is to use MicrosoftAjax.js, which does understand __type, and then somehow use it in conjunction with GeoJSON (I don't know if that's even possible, but just throwing it out there as a potential idea)
来源:https://stackoverflow.com/questions/9363990/rename-type-field-in-wcf-services