如何提取JSON指定字段值并转换为C#对象
C# 从JSON中提取指定字段转对象实现方法
你不需要手动裁剪完整JSON内容,直接通过JSON反序列化即可自动提取需要的字段,多余字段会被序列化器默认忽略,以下是两种最常用的实现方案:
第一步:定义目标C#模型类
仅需要定义你要提取的4个字段对应属性即可,无需覆盖JSON全量字段:
public class CountryInfo { public string Name { get; set; } public long Population { get; set; } public double Area { get; set; } public List<string> AltSpellings { get; set; } }
说明:
Population选用long类型是为了避免人口数值超过int类型上限出现溢出;AltSpellings用string[]替代List<string>也可正常反序列化。
方案1:使用.NET内置System.Text.Json实现(推荐,无第三方依赖)
适用于.NET Core 3.0、.NET 5及以上版本,不需要额外安装NuGet包:
using System.Text.Json; // 替换为你持有的原始JSON字符串 string rawJson = "你的原始JSON内容"; // 配置反序列化规则:支持字段名大小写不敏感匹配(适配JSON小驼峰命名和C#大驼峰属性的映射) var serializeOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; // 执行反序列化,自动映射指定4个字段 CountryInfo result = JsonSerializer.Deserialize<CountryInfo>(rawJson, serializeOptions);
方案2:使用Newtonsoft.Json(Json.NET)实现
适用于.NET Framework等老版本项目,需要先通过NuGet安装Newtonsoft.Json包:
using Newtonsoft.Json; // 替换为你持有的原始JSON字符串 string rawJson = "你的原始JSON内容"; // 执行反序列化,默认支持大小写不敏感匹配、自动忽略多余字段 CountryInfo result = JsonConvert.DeserializeObject<CountryInfo>(rawJson);
反序列化后得到的字段对应值
result.Name:Indiaresult.Population:1380004385result.Area:3287590.0result.AltSpellings:包含4个元素的字符串集合:"IN"、"Bhārat"、"Republic of India"、"Bharat Ganrajya"
内容的提问来源于stack exchange,提问作者Saranya
相关产品推荐
相关产品推荐

