0

My web api is returning a set of objects which are differ from the Domain object. Forexample, I my domain has an Employee class but I don't want to expose all the members of the Employee class in my api so I created another class called EmployeeApiModel.

Now my WebApi is returning a List of EmployeeApiModel but I want to be able to specify the name to which it should serialize to. That is instead of <EmployeeApiModel> tag in the xml, I want to get <Employee> but without changing the fact that the underlying class which is being serialized is EmployeeApiModel.

How can I achieve this?

shashi
  • 4,616
  • 9
  • 50
  • 77

2 Answers2

3

Technically, Web Api support both json and xml based on content negotiation mechanism, Json is the default format, if you want to receive xml, just put on header:

Accept: application/xml

To understand more content negotiation, access this

Since you want your api support both json and xml, you should use DataContract and DataMember Attribute for serialization for your model: EmployeeApiModel, something like:

[DataContract(Name = "Employee")]
public class EmployeeApiModel
{
    [DataMember(Name = "Name2")]
    public string Name { get; set; }

    [DataMember]
    public string Email { get; set; }
}

See more on this blog-post

cuongle
  • 74,024
  • 28
  • 151
  • 206
0

You can control the output of your serialized XML by using various Attribute tags.

[XmlRoot("Employee")]
Public class EmployeeApiModel
{
    [XmlElement("fname")]
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int age { get; set; }
}

this will produce XML like:

<Employee>
    <fname>John</fname>
     <LastName >Smith</LastName >
    <age>24</age>  
</RootElementsName>

You can read more about the various XML modifiers here: http://msdn.microsoft.com/en-us/library/e123c76w.

If you want to use existing XML modifiers for JSON, check out this post: Serialize .Net object to json, controlled using xml attributes

Community
  • 1
  • 1
Robert H
  • 11,520
  • 18
  • 68
  • 110
  • 3
    This does not seem to work with the Web Api. I added XmlRoot but still get the same ApiModel as the root. – shashi Aug 09 '12 at 15:28