简体   繁体   English

使用Newtonsoft.Json进行反序列化

[英]Deserialization with Newtonsoft.Json

I have my controller, which can send an json object and recieve the same object again. 我有我的控制器,它可以发送一个json对象并再次接收相同的对象。 My problem is that the AjaxSaveFoo creates a Foo Object but I always get an empty object back. 我的问题是AjaxSaveFoo创建了一个Foo对象,但我总是得到一个空对象。 How do I create the deserialization ? 如何创建反序列化

/// <summary>
/// Returns a foo
/// </summary>
/// <returns></returns>
public JsonNetResult AjaxLoadFoo()
{
    return new JsonNetResult
    {
       Data = new Foo()
    };
}

/// <summary>
/// Saves a foo
/// </summary>
/// <returns></returns>
public JsonNetResult AjaxSaveFoo(Foo foo) //who tries to deserialize this!!, its always empty
{

    return new JsonNetResult
    {
        Data = foo
    };

}

My client side.. 我的客户方..

$.ajax({
    type: "POST",
    url: "AjaxSaveFoo",
    data: JSON.stringify(this._FooObj),
    success: this.saveSucces,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    error: this.saveFailure
});

Foo when its sent down.. Foo什么时候送下来..
{ {

"CustomerNumber": 2,
"CustomerStatus": "1"
}

Foo when its submitted (POST) Foo提交时(POST)

{"CustomerNumber":2,"CustomerStatus":"1"}

The object you are passing up is not getting transformed into a Foo object correctly. 您传递的对象未正确转换为Foo对象。

Try changing the signature to input a string and then try and deserialize: 尝试更改签名以输入字符串,然后尝试反序列化:

public JsonNetResult AjaxSaveFoo(string json)
{
   var foo = JsonConvert.DeserializeObject<Foo>(json);
   return new JsonNetResult
   {
      Data = foo
   };
} 

I found the bug.... 我发现了这个bug ....

The url should have been AjaxSaveFoo/ instead of AjaxSaveFoo. url应该是AjaxSaveFoo /而不是AjaxSaveFoo。 This gave me a 301 from the server (adding the /) But also resulted in the client using a GET and therefore not populating data.. sigh 这给了我一个301从服务器(添加/)但也导致客户端使用GET,因此没有填充数据.. 叹息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM