My application mainly uses JSON to communicate back and forth with the front end client. However, there is an Import/Export component to my application which will expose and accept XML to and from a file.

When serializing the JSON I use JSON.NET (default Web API behavior). When serializing the XML I use the DataContractSerializer (default Web API behavior).

When serializing to XML I would like to not include certain collections and properties associated with an object in the XML.

  1. JsonIgnore will only do this when serializing JSON, so that won't work.

  2. IgnoreDataMember will do this for BOTH JSON and XML, so that won't work. (In older versions it seems like this might have worked, but alas the world is ever changing).

  3. ShouldSerialize{PropertyName} only seems to work with JSON too, so that won't work.

This is an Entity Framework Database First project that generates the entities via T4 template from the edmx file, so I really do not want to use the OPT-IN approach of setting DataContract and Datamember on each field. However, I did try and was able to ignore by

    [OnSerializing]
    public void IgnoreIfXml(StreamingContext context)
    {
        if (IsXML)
        {
            this.ThingIwantToIgnore = null;
        }
    }

And setting the emit default value to false on the member:

    [DataMember(EmitDefaultValue=false)]
    public virtual ICollection<AThing> ThingIwantToIgnore { get; set; }

IsXml is a propperty that I set based on the controller call which is true if the client is expecting xml back.

The problem with this approach is that there are some nullable and other fields where the default value is still something I want to return to the front end, so this won't work either. I then tried using the XMLSerializer by setting UseXmlSerializer = true in the Global.asax, but then my application just kept returning JSON instead of XML as if it was unable to serialize to XML. I also would like to avoid going down this route if at all possible.

Does anyone have any suggestions as to how to ignore only if serializing to XML? I would particular be interested in suggestions that included sticking with the DataContractSerializer as the XmlSerializer supports a narrower set of types.

有帮助吗?

解决方案 2

I know this is old but was going thru my SO account and thought I'd share my solution in case anyone is curious.

I ended up creating DTOs for the XML objects which had the specific fields I wanted and then just serialized those DTOs.

其他提示

The import/export component does not export objects that are identical to your EF objects. This is best reflected if you convert the EF objects to DTO objects in your Web API. See this for an example. You can then easily control the format of the XML using DataContract and DataMember attributes on your DTO classes.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top