MVC4 Web API Default JSON Serializer
I have stumbled up on some thing today. The below are my sample classes.
public class Employee
{
public string Name{get;set;}
Public Department Dept {get;set;}
public IList<Roles> Roles;
}
public Department{
public string Name{get;set;}
}
public Role {
public string Name{get;set;}
}
sampleApiController : ApiContrller{
public IEnumerable<string> Get(){
return new List<string>{"Pavan", "Josyula"};
}
public Employee GetEmp(int id){
Employee e = new Employee();
e.Dept = "IT";
e.Name="Pav";
IList<Roles> r = new IListRoles();
r.Add(new Role{Name="Integrator"});
e.Roles = r;
return e;
}
}
Now when I call this GetEmp Method from my broswer it is always giving me response in JSON format no matter what my content type in AcceptHeaders. But when I call my Get method, it returns collection of strings in XML format also it acts based on accept verb in request header. Can some body tell me the reason for this default JSON behaviour for custom types.
This is because XmlSerializer can't serialize IList<T>
. Please read below answer for more details: