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

JSON中MdId字段反序列化为C# List<string>失败求助

问题:JSON反序列化时单个字符串转List失败

在将JSON字符串反序列化为C#对象时,遇到单个字符串无法转换为List<string>的问题,即使给字段添加了[JsonProperty]特性仍未解决。

C#实体类

public class PendingPatientDocumentRecord
{
    public int PatientDocumentFileMapId;
    public short ContextTypeId;
    public string PatientVisitId;
    public List<string> BillingIds;
    public DateTime? DateOfService;

    [JsonProperty("MdId")]
    public List<string> MdId;
}

反序列化代码

List<PendingPatientDocumentRecord> pendingDocuments = JsonConvert.DeserializeObject<List<PendingPatientDocumentRecord>>(pendingDocumentsJson);

待反序列化的JSON字符串

[
  {
    "PatientDocumentFileMapId":12,
    "ContextTypeId":3,
    "DateOfService":"08/31/2022",
    "MdId":"ala"
  }
]

错误信息

Error converting value "ala" to type 'System.Collections.Generic.List`1[System.String]'. Path '[0].MdId'


问题原因

报错核心并非字段映射问题([JsonProperty]已正确关联JSON与C#字段名),而是JSON中的MdId是单个字符串值,但C#中定义的是List<string>类型,Newtonsoft.Json无法自动将单个字符串转换为字符串列表。

解决方案

方案1:修改JSON格式(推荐,符合规范)

将JSON中的MdId改为数组格式,即使仅含一个元素:

[
  {
    "PatientDocumentFileMapId":12,
    "ContextTypeId":3,
    "DateOfService":"08/31/2022",
    "MdId": ["ala"]
  }
]

方案2:修改C#代码适配现有JSON

若无法修改JSON,可通过添加自定义JSON转换器处理单个字符串转列表的场景:

步骤1:创建自定义转换器

public class SingleOrListConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(List<T>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        if (token.Type == JTokenType.Array)
        {
            return token.ToObject<List<T>>();
        }
        return new List<T> { token.ToObject<T>() };
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var list = value as List<T>;
        if (list?.Count == 1)
        {
            serializer.Serialize(writer, list[0]);
        }
        else
        {
            serializer.Serialize(writer, list);
        }
    }
}

步骤2:在MdId字段上应用转换器

public class PendingPatientDocumentRecord
{
    public int PatientDocumentFileMapId;
    public short ContextTypeId;
    public string PatientVisitId;
    public List<string> BillingIds;
    public DateTime? DateOfService;

    [JsonProperty("MdId")]
    [JsonConverter(typeof(SingleOrListConverter<string>))]
    public List<string> MdId;
}

此修改后,无论是单个字符串还是数组格式的MdId,都能正确反序列化为List<string>。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:24:42