Trying to pass this object between two modules:
public class Transaction
{
public string ID { get; set; }
public string ErrorMessage { get; set; }
public int ErrorCode { get; set; }
}
Serialization:
transaction.ErrorMessage = "temptemptemp";
transaction.ErrorCode = 123;
transaction.ID = "0";
return Ok(JsonConvert.SerializeObject(transaction));
Deserialization:
using (WebClient webClient = new WebClient())
{
string json = webClient.DownloadString(url);
Transaction transaction = JsonConvert.DeserializeObject<Transaction>(json);
}
in the debug window, I see the two strings like this:
and so I'm getting the following exception:
Error converting value "{"ID":"0","ErrorMessage":"temptemptemp","ErrorCode":123}" to type 'WebService.Transaction'. Path '', line 1, position 75.
You are double-serializing your transaction
object. First you serialize it to a JSON string by manually calling
var jsonString = JsonConvert.SerializeObject(transaction);
Then you pass it to Ok<T>(T content)
which also serializes its incoming value:
return Ok(jsonString);
Since the incoming value is a string, Ok()
escapes it as a required by the JSON standard for representation of a string literal.
Instead, let asp.net serialize it for you:
return Ok(transaction);
If you want to force JSON to be returned, you can use Json<T>(T content)
:
return Json(transaction);