首页 > 解决方案 > 无法从 System.String 转换或转换为自定义对象或模型

问题描述

我正在尝试将来自 HTTP 响应的 JSON 文本反序列化到特定模型。但它失败了,但有以下例外:

消息=将值“{“Id”:“1”,“UserName”:“RK”}”转换为类型“ConsoleApp5.TestData”时出错。

内部异常 1:ArgumentException:无法从 System.String 转换或转换为 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"
}

标签: c#jsonjson-deserialization

解决方案


我认为问题出在 JSON 上。如果你仔细观察 JSON。你会发现data值是用引号引起来的"{\"Id\":\"1\",\"UserName\":\"RK\"}",这意味着它将把它当作一个字符串来对待。

因此,如果您将数据类型指定为字符串,它将起作用。或者您需要做一些解决方法才能将其作为对象。

public class JsonResponseStruct
{
    public string Data;

}

推荐阅读