Ensure the object you are trying to convert to has a default (empty) constructor.
Rule of thumb: If you want to deserialize to an object, you need to make it simple for the objects to be created. These guidelines can help:
This JSON string/object for example:
{ Name: "John Doe", Phone: "123-456-7890", Pets: [ "dog", "cat", "snake" ] }
can be converted to an object from the following class:
public class Person {
public string Name { get; set; }
public string Phone { get; set; }
public string[] Pets { get; set; }
}
or this one:
public class Person {
public string Name { get; set; }
public string Phone { get; set; }
public string[] Pets { get; set; }
public Person() {}
public Person(string name, string phone) {
Name = name;
Phone = phone;
}
}
or this one:
public class Person {
public string Name { get; set; }
public string Phone { get; set; }
public string[] Pets { get; set; }
public Person() {}
}
but not this one
public class Person {
public string Name { get; set; }
public string Phone { get; set; }
public string[] Pets { get; set; }
public Person(string name, string phone) {
Name = name;
Phone = phone;
}
}
Now let ASP.NET MVC 4 do the rest
public class PersonController : ApiController
{
// .. other actions
public HttpResponseMessage PostPerson(Person person)
{
if ( null != person)
// CELEBRATE by doing something with your object
else
// BE SAD and throw and exception or pass an error message
}
// .. other actions
}
If your class cannot have a default constructor or if you don't have access to the source code for the class, you can create an adapter class that
- has a default constructor
- exposes those properties that need to be public
Using the Person class above with no default constructor, an adapter could look like
public class PersonAdapter {
public Person personAdaptee;
public string Name {
get { return personAdaptee.Name; }
set { personAdaptee.Name = value }
}
public string Phone {
get { return personModel.Phone; }
set { personModel.Phone = value; }
}
public string[] Pets {
get { return personAdaptee.Pets; }
set {personAdaptee.Pets = value }
}
public PersonAdapter() {
personAdaptee = new Person("", "", null);
}
}
Now let ASP.NET MVC 4 do the rest
public class PersonController : ApiController
{
// .. other actions
public HttpResponseMessage PostPerson(PersonAdapter person)
{
if ( null != person)
// CELEBRATE by doing something with your object
else
// BE SAD and throw and exception or pass an error message
}
// .. other actions
}