You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ArgumentException:无法将System.String转换为Ricoverato的问题排查

解决方案:ArgumentException: 无法从System.String转换为gsMedicApp.Pages.Ricoverato

这个错误核心是JSON反序列化时类型不匹配,结合你提到的JSON含大量反斜杠的情况,大概率是以下几种问题之一,对应解决方法如下:

1. API返回的是「转义后的JSON字符串」而非原始JSON数组

如果API返回内容是类似 "[{\"IdRicovero\":1,...}, {...}]" 这种带反斜杠的格式,说明返回的是被包装成字符串的JSON数组,直接反序列化成List<Ricoverato>会失败——因为外层是字符串类型,不是数组。

解决步骤:
先解析外层字符串得到原始JSON,再反序列化为实体类数组:

// 假设responseContent是API返回的带反斜杠的字符串
using Newtonsoft.Json;

// 第一步:解析外层字符串,获取原始JSON数组
string rawJsonArray = JsonConvert.DeserializeObject<string>(responseContent);

// 第二步:反序列化为Ricoverato列表
List<Ricoverato> ricoveratiList = JsonConvert.DeserializeObject<List<Ricoverato>>(rawJsonArray);

若使用System.Text.Json,代码调整为:

using System.Text.Json;

string rawJsonArray = JsonSerializer.Deserialize<string>(responseContent);
List<Ricoverato> ricoveratiList = JsonSerializer.Deserialize<List<Ricoverato>>(rawJsonArray);

2. 反序列化目标类型错误

如果错误地将JSON数组反序列化为单个Ricoverato对象,或未指定为列表类型,会直接触发转换错误。

错误示例:

// 错误:把数组当成单个对象反序列化
Ricoverato ricoverato = JsonConvert.DeserializeObject<Ricoverato>(responseContent);

正确写法:

// 正确:指定为列表类型
List<Ricoverato> ricoveratiList = JsonConvert.DeserializeObject<List<Ricoverato>>(responseContent);

3. Ricoverato类与JSON字段映射不匹配

如果类属性名和JSON字段名不一致(如大小写差异、字段名不同),且未添加映射特性,反序列化时会导致字段绑定失败,进而触发类型转换异常。

解决方法:添加字段映射特性,确保属性与JSON字段一一对应:

using Newtonsoft.Json; // Newtonsoft.Json用JsonProperty
// 或使用System.Text.Json的JsonPropertyName

public class Ricoverato
{
    [JsonProperty("id_ricovero")] // 对应JSON中的"id_ricovero"字段
    public int IdRicovero { get; set; }

    [JsonProperty("nome_paziente")]
    public string NomePaziente { get; set; }

    // 其他属性同理,逐一映射JSON字段
}

4. API返回的是包含数组的包装对象

如果API返回的JSON结构是类似 {"data": [...], "status": 200} 的包装对象(而非直接返回数组),需要先定义容器类再反序列化:

public class HospitalizedApiResponse
{
    [JsonProperty("data")]
    public List<Ricoverato> Ricoverati { get; set; }

    [JsonProperty("status")]
    public int StatusCode { get; set; }
}

// 反序列化时先解析容器类
var apiResponse = JsonConvert.DeserializeObject<HospitalizedApiResponse>(responseContent);
List<Ricoverato> ricoveratiList = apiResponse.Ricoverati;

内容的提问来源于stack exchange,提问作者stighy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 11:33:47