当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - 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

分享给朋友:
您可能感兴趣的文章:
随机阅读: