I am trying to deserialize JSON text coming from HTTP response to a particular Model. But it fails with below exception:
Message=Error converting value "{"Id":"1","UserName":"RK"}" to type 'ConsoleApp5.TestData'.
Inner Exception 1: ArgumentException: Could not cast or convert from System.String to ConsoleApp5.TestData.
Here's code:
static async Task Main()
{
var jsonText =
"{\n \"args\": {}, \n \"data\": \"{\\\"Id\\\":\\\"1\\\",\\\"UserName\\\":\\\"RK\\\"}\", \n \"files\": {}, \n \"form\": {}, \n \"headers\": {\n \"Accept\": \"application/json\", \n \"Content-Length\": \"26\", \n \"Content-Type\": \"application/json; charset=utf-8\", \n \"Host\": \"httpbin.org\", \n \"X-Amzn-Trace-Id\": \"Root=1-60c3783a-1f273fd11e5828436035ac22\"\n }, \n \"json\": {\n \"Id\": \"1\", \n \"UserName\": \"RK\"\n }, \n \"method\": \"POST\", \n \"origin\": \"223.184.90.85\", \n \"url\": \"https://httpbin.org/anything\"\n}\n";
var output = JsonConvert.DeserializeObject<JsonResponseStruct>(jsonText);
}
public class JsonResponseStruct
{
public TestData Data;
}
public class TestData
{
public string Id;
public string UserName;
}
JSON:
{
"args": {},
"data": "{\"Id\":\"1\",\"UserName\":\"RK\"}",
"files": {},
"form": {},
"headers": {
"Accept": "application/json",
"Content-Length": "26",
"Content-Type": "application/json; charset=utf-8",
"Host": "httpbin.org",
"X-Amzn-Trace-Id": "Root=1-60c3783a-1f273fd11e5828436035ac22"
},
"json": {
"Id": "1",
"UserName": "RK"
},
"method": "POST",
"origin": "223.184.90.85",
"url": "https://httpbin.org/anything"
}