c# - 无法从 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"
}
解决方案
我认为问题出在 JSON 上。如果你仔细观察 JSON。你会发现data
值是用引号引起来的"{\"Id\":\"1\",\"UserName\":\"RK\"}"
,这意味着它将把它当作一个字符串来对待。
因此,如果您将数据类型指定为字符串,它将起作用。或者您需要做一些解决方法才能将其作为对象。
public class JsonResponseStruct
{
public string Data;
}
推荐阅读
- python - 带有日期时间的 Python os.rename 不断保存多个同名文件
- c++ - 给定数字的其他 2 个毕达哥拉斯三元组
- c# - 首先创建代码 postgres 数据库失败:未提供密码,但后端需要密码(在 MD5 中)
- php - Apache、PHP 5.6 或 7.0:未加载库:openssl/lib/libcrypto.1.0.0.dylib 使用 Homebrew
- django - 基于国外模型字段值django的唯一约束
- google-chrome-devtools - DevTools - 关闭问题警告?
- macos-catalina - MacOS升级到10.15.X(Catalina)后无法打开JDK
- graphql - 如何在 appsync 中定义解析器以获取 graphQL 中特定日期之间的数据范围
- python - 将数据透视表中的 15 分钟间隔使用数据转换为 60 分钟格式
- python - Matplotlib 轴混淆