Reputation: 10679
I am building 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 the following:
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<surname>John</surname>
<name>Titor</name>
</Person>
I now need an annotation set which lets me change the default inner objects' names, for example I'd like to change surname
into msurname
. I have tried adding the following:
[XmlElement("msurname")]
annotation, but that only works if the Accept
header of my request contains application/xml
(of course). I have tried and used the [DataMember]
annotation, which is completely ignored.
Is there an annotation set I can use with this ApiController in WebAPI for serialization into both XML and JSON formats? Thank you.
EDIT: correction, if I use the [DataMember]
and [DataContract]
annotation, I get the desired behaviour with JSON serialization, but not with the XML. The opposite thing happens if I use [XmlElement]
.
Upvotes: 3
Views: 4842
Reputation: 142014
The behaviour you are seeing with DataMember is because by default WebAPI uses XmlSerializer, not DataContractSerializer. However JSON uses the JSONDataContractSerializer by default at the moment. However in the future it will not. You can change the XML to the XmlDataContractSerializer by setting
GlobalConfiguration.Config.Formatters.XmlDataContractSerializer = true;
That way, both the JSON and XML formats will use the DataContractSerializer.
Upvotes: 5
Reputation: 58444
The way it works is that you will be dealing with Formatters. The XML data you are getting is produced by XmlMediaTypeFormatter
(XmlMediaTypeFomatter Class).
I am not aware of any built-in feature as you describe but it is fairly easy to write your own formatter.
Here is an example of a custom formatter implementation, you will get the idea:
Using JSON.NET with ASP.NET Web API
Upvotes: 0
Reputation: 10221
The two serializers do use different Attributes to handle renaming of columns etc.
There is no way to unify that you will need to have both Attributes present.
You could however use a different XML/JSON serializer that recognizes the other ones attributes.
UPDATE
You might also try the DataAnnotations
and see if the serializers recognize them
Upvotes: 0