确保您尝试转换为的对象具有默认(空)构造函数。
经验法则:如果要反序列化为对象,则需要使创建对象变得简单。这些指南可以帮助:
所有要传递的属性必须是公共的
该对象需要能够在没有任何参数的情况下构造。
这个 JSON 字符串/对象例如:
{ Name: "John Doe", Phone: "123-456-7890", Pets: [ "dog", "cat", "snake" ] }
可以从以下类转换为对象:
public class Person {
public string Name { get; set; }
public string Phone { get; set; }
public string[] Pets { get; set; }
}
或者这个:
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;
}
}
或者这个:
public class Person {
public string Name { get; set; }
public string Phone { get; set; }
public string[] Pets { get; set; }
public Person() {}
}
但不是这个
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;
}
}
现在让 ASP.NET MVC 4 完成剩下的工作
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
}
如果您的类没有默认构造函数,或者您无权访问该类的源代码,您可以创建一个适配器类
使用上面没有默认构造函数的 Person 类,适配器可能看起来像
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);
}
}
现在让 ASP.NET MVC 4 完成剩下的工作
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
}