开发者

REST XML serialization of lists of abstract classes with "i:type" attribute - how to convert that to tag name?

I'm writing a REST WCF service with开发者_JAVA百科 methods to retrieve a collection of resources and a single resource. My resources are classes based on a single abstract class. In my method to retrieve a collection I have:

[WebGet(UriTemplate = "")]
[ServiceKnownType(typeof(File)), ServiceKnownType(typeof(Text))]
List<ResourceBase> GetCollection();

and that produces XML that looks like this:

<ArrayOfResourceBase xmlns="..." xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <ResourceBase i:type="Text">
    ...
    </ResourceBase>
    <ResourceBase i:type="File">
    ...
    </ResourceBase>
</ArrayOfResourceBase>

My single object method looks like this:

[WebGet(UriTemplate = "{id}")]
[ServiceKnownType(typeof(File)), ServiceKnownType(typeof(Text))]
ResourceBase Get(string id);

and produces XML like this:

<Text xmlns="..." xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
...
</Text>

Is there a way to get those two xml parts to look the same, that is either to get rid of "i:type" tags in ArrayOf... and convert them to tag name, or force them in the single object response?


There may be several solutions here, but I can think of a few right away:

  1. Change the custom DataContract name of the DataContract class ResourceBase to always be Text. Like so:

    [DataContract(Name="Text")] class ResourceBase { ... }

  2. Plug in a DataContractSurrogate to special-case this type

  3. Plug in a custom DataContractSerializerOperationBehavior that plugs in a custom DataContractSerializer child that special cases this type

  4. Use XmlSerializer. See this blog post.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜