我的Web API C#.net服务器无法反序列化JSON对象

时间:2015-05-03 15:23:59

标签: c# json asp.net-web-api2

这是我的客户代码

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,然后添加:“”。这不是我想要的。

2 个答案:

答案 0 :(得分:1)

您的代码中存在几个问题:

  1. 反序列化区分大小写,因此JS端的属性必须与服务器端的属性具有相同的大小写
  2. 您需要直接将person对象作为参数传递,而不是作为对象的person属性包含在内
  3. 虽然它通常不会受到伤害,但您不需要对对象进行字符串化。 jQuery ajax将自动为您执行
  4. 关于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天的时间来真正弄清楚真正的原因(据说)