这是我的客户代码
var sayeed = { firstname: "Sayeed", surname: "Alquiaty" };
alert(JSON.stringify({ person: sayeed }));
$.ajax({
url: "api/parent",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ person: sayeed }),
success: function(response) {
response ? alert("It worked!") : alert("It didn't work.");
}
});
在服务器端
public class Person {
public string Firstname { get; set; }
public string Surname { get; set; }
}
//Here I am able to receive object but is is not FirstName = null and Surname = null
// POST api/parent
public bool PostParent(Person person) {
return person != null;
}
因此客户端获得成功消息,但实际上JSON对象不是反序列化
我尝试了其他方法,比如使用JObject但是这会破坏Json对象,我的意思是它将客户端对象转换为Key,然后添加:“”。这不是我想要的。
答案 0 :(得分:1)
您的代码中存在几个问题:
person
属性包含在内ajax
将自动为您执行关于1,您可以设置Web API序列化程序将服务器端PascalCase转换为客户端camelCase,反之亦然,但在客户端和服务器端之间转换属性名称时仍需要考虑这一点:
var jsonformatter
= GlobalConfiguration.Configuration.Formatters.JsonFormatter;
jsonformatter.SerializerSettings.ContractResolver
= new CamelCasePropertyNamesContractResolver();
答案 1 :(得分:0)
感谢大家帮我解决这个问题。 但我可以发现我的服务器端代码中的错误
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = true;
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.XmlFormatter.UseXmlSerializer = false;
所以现在我评论了上面的配置设置,每件事情都开始完美。但这花了我2天的时间来真正弄清楚真正的原因(据说)