0

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"
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Raj
  • 664
  • 7
  • 23
  • 1
    `data` itself is a string within your JSON, not an object. You'll need to deserialize the outer object with `data` as a `string` and then deserialize `data`. – ProgrammingLlama Jun 11 '21 at 15:28

1 Answers1

0

I think the problem is with the JSON. If you carefully observe the JSON. You will find data value is in inverted comma's "{\"Id\":\"1\",\"UserName\":\"RK\"}" which means it will treat it as a string.

So if you will specify the data type as a string it would work. Or you need to do some workaround to get it as the object.

public class JsonResponseStruct
{
    public string Data;

}
x3weird-
  • 74
  • 2
  • 11
  • Thanks! It helped me to resolve the issue. I changed the Data as string and then again deserialized the output data as TestData. – Raj Jun 12 '21 at 02:19