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

DataContractJsonSerializer反序列化如何处理JSON与类属性名不匹配问题

解决方案

你当前使用的是DataContractJsonSerializer序列化组件,只需通过数据契约特性手动指定属性和JSON字段的映射关系即可,不需要修改原有反序列化逻辑。

操作步骤

  1. 引用命名空间System.Runtime.Serialization
  2. 给所有模型类(Root、CpuItem、DiskItem、MemItem)添加[DataContract]特性
  3. 给每个类的属性添加[DataMember]特性,通过Name参数指定对应JSON中的原始字段名

代码示例

using System.Runtime.Serialization;
using System.Collections.Generic;

// Root类定义示例
[DataContract]
public class Root
{
    // 映射JSON中小写的cpu字段
    [DataMember(Name = "cpu")]
    public List<CpuItem> Cpu { get; set; }

    // 映射JSON中小写的disk字段
    [DataMember(Name = "disk")]
    public List<DiskItem> Disk { get; set; }

    // 映射JSON中小写的mem字段
    [DataMember(Name = "mem")]
    public List<MemItem> Mem { get; set; }
}

// CpuItem类定义示例,适配带空格等特殊格式的JSON字段
[DataContract]
public class CpuItem
{
    [DataMember(Name = "Cpustatus")]
    public string CpuStatus { get; set; }

    // 映射JSON中带空格的"Brand Name"字段
    [DataMember(Name = "Brand Name")]
    public string BrandName { get; set; }

    [DataMember(Name = "Size")]
    public string Size { get; set; }
}

其他说明

如果后续更换序列化组件,也有对应的映射特性可选:

  • 若使用System.Text.Json:用[JsonPropertyName("原始字段名")]特性
  • 若使用Newtonsoft.Json:用[JsonProperty("原始字段名")]特性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 07:12:02