views:

136

answers:

1

Greetings

I'm trying to convert a "collection of collections" into better looking xml. Basically, I want to lie to the service consumer and make it look like there's a real object.

This is what WCF creates automatically

<EntityPropertyCollection xmlns="http://schemas.datacontract.org/2004/07/CustomSerializer" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt;
 <EntityProperty>
  <Name>Test</Name>
  <Value i:nil="true"/>
 </EntityProperty>
 <EntityProperty>
  <Name>Test2</Name>
  <Value i:type="EntityPropertyCollection">
   <EntityProperty>
    <Name>Nested1</Name>
    <Value i:nil="true"/>
   </EntityProperty>
   <EntityProperty>
    <Name>Nested2</Name>
    <Value i:nil="true"/>
   </EntityProperty>
  </Value>
 </EntityProperty>
</EntityPropertyCollection>

This is what I'd like to achieve

<Something>
 <Test i:nil="true"/>
 <Test2 i:type="Something">
  <Nested1 i:nil="true"/>
  <Nested2 i:nil="true"/>
 </Test2>
</Something>

A custom serializer for a particular type (EntityProperyCollection) would be good, but other posts indicate that's not an option.

I looked at Data Contract Surrogates. I think I could generate a custom type and allow the DataContractSerializer to serialize the generated type. But, I'm hoping there's a simpler solution.

Any suggestions?

Thanks for the help.

A: 

You could implement IXmlSerializable on your return object and do the serialization manually, or just return stream and use an XmlWriter to create exactly the XML you want.

Darrel Miller
I tried that. It works for Xml, as you said. I couldn't find a JSON equivalent for the REST services, though.DataContractSerializer is sealed, unfortunately. I think I'm back to using the surrogate; generate a type and let the serializers work as they usually do.Thanks for the help
Jay Allard
Check in the WCF REST Starter Kit. In there is a library called Microsoft.Http and Microsoft.Http.Extensions. In there are some Json serializers and deserializers. You should be able to use those to generate a JSON Stream. These classes are intended for use on the client, but they work just as well on the server.
Darrel Miller
Thanks for the suggestion. I wasn't able to work on this today. When I get back to it, I'll let you know how it goes.
Jay Allard