简体   繁体   中英

Deserialization with Newtonsoft.Json

I have my controller, which can send an json object and recieve the same object again. My problem is that the AjaxSaveFoo creates a Foo Object but I always get an empty object back. 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..
{

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

Foo when its submitted (POST)

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

The object you are passing up is not getting transformed into a Foo object correctly.

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....

The url should have been AjaxSaveFoo/ instead of 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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