无法从 System.String 转换或转换为自定义对象或模型

Could not cast or convert from System.String to Custom Object or Model

我正在尝试将来自 HTTP 响应的 JSON 文本反序列化到特定模型。但它因以下异常而失败:

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.

代码如下:

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"
}

我认为问题出在 JSON。如果你仔细观察JSON。您会发现 data 值在引号 "{\"Id\":\"1\",\"UserName\":\"RK\"}" 中,这意味着它会将其视为字符串。

因此,如果您将数据类型指定为字符串,它就可以工作。或者您需要做一些变通方法才能将其作为对象获取。

public class JsonResponseStruct
{
    public string Data;

}