Changing the Name of Internal Objects for ASP.NET MVC 4 WebAPI Serialization (XML / JSON)

I am creating a RESTful web service with the new Microsoft MVC 4 ApiController class and WebAPI . I have a Person class:

public class Person
    public string surname { get; set; }
    public string name{ get; set; }


and the default HTTP GET method works, returning this:

<Person xmlns:xsi="" xmlns:xsd="">


Now I need a set of annotations that allows me to change the default internal object names, for example, I would like to change surname

to msurname

. I tried to add the following:



but this only works if Accept

my request header contains application/xml

(of course). I tried and used annotation [DataMember]

which is completely ignored.

Is there a set of annotations I can use with this ApiController in WebAPI to serialize to XML and JSON? Thank.

EDIT : The fix is ​​if I use annotation [DataMember]

and [DataContract]

, I get the desired behavior with JSON serialization, but not XML. The opposite thing happens if I use [XmlElement]



source to share

3 answers

The behavior you see with the DataMember is due to the fact that by default the WebAPI uses the XmlSerializer and not the DataContractSerializer. However, JSON uses JSONDataContractSerializer by default. However, this will not happen in the future. You can change XML to XmlDataContractSerializer by setting

GlobalConfiguration.Config.Formatters.XmlDataContractSerializer = true;


Thus, both JSON and XML formats will use the DataContractSerializer.



The two serializers use different attributes to handle column renaming etc.

There is no way to unify that you will need to have both attributes.

However, you can use a different XML / JSON serializer that recognizes other attributes.

You can also try DataAnnotations

and see if serializers recognize them



As it works, you will be dealing with Formatters . The resulting XML data is generated using the XmlMediaTypeFormatter

( XmlMediaTypeFomatter Class ).

I don't know of any built-in function that you describe, but it's pretty easy to write your own formatter.

Here is an example of a custom formatting implementation, you get the idea:




All Articles