问题
I try to make a simple call to a server-side method in ASP.NET MVC 4. I do this by making a jQuery call to a method. The method gets called and the properties are correct, but the response of this method is not correct. I try to serialize an .NET object using JSON.NET.
I can see I get the following response (using FireBug):
"{\"VisitorId\":\"11a0606b-5336-4fa7-b50f-3edf97d8301b\",\"PhoneToTransfer\":\"61793650\",\"PhoneToNotify\":\"\",\"EmailToNotify\":\"mcoroklo@gmail.com\",\"EmailToTransfer\":\"\",\"OrderState\":\"PaymentPending\",\"DestinationAddress\":\"1Ccypfi3rnXosUgY6p1sQVXFyddFvwLFEJ\",\"TransactionHash\":\"\",\"Value\":12.0,\"Confirmations\":-1,\"TransactionDate\":\"2013-01-09T22:36:33.7991116+01:00\"}"
This doesn't parse as correct JSON, and I have no idea why. Also, the "JSON" tab in Firebug says "There are no properties to show for this object".
I am pretty sure my content-type and dataType is correct on the call.
This is my code to make the JSON - using The JSON.NET library:
[HttpPost]
public JsonResult StartPurchase(string phoneReceiver, string emailNotify, string value)
{
if (ModelState.IsValid)
{
BlockchainPayments block = new BlockchainPayments();
var address = block.GetAddress(BtcContext.PurchaseSession);
decimal val = 0;
decimal.TryParse(value, out val);
var ps = new PurchaseService();
var purchase = ps.StartPurchase(BtcContext.PurchaseSession, phoneReceiver, emailNotify, address.destination, val);
return Json(JsonConvert.SerializeObject(purchase));
}
return Json("Error");
}
This is the jQuery call:
$.ajax({
type: "POST",
url: url,
data: dataToSend,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('Awesome destination succes');
},
error: function (date) {
alert('An occurred while purchasing. Please try again later');
}
});
Any idea why it's not returning valid JSON? And any ideas on how to solve it?
回答1:
It looks like you are double encoding it, just use one conversion method, e.g. return Json(purchase);
回答2:
return Json
already serializes an object I believe. Looks like you're getting double serialization.
来源:https://stackoverflow.com/questions/14247131/jsonresult-not-returning-valid-json-serializing-going-wrong