在C#中反序列化指定JSON文件的技术问题
在C#中反序列化指定JSON文件的技术问题
嘿,我来帮你搞定这个JSON反序列化的事儿!先理清楚你给的内容:
你有这样的JSON文件内容:
{ "@odata.context": "https://mmtruevalves.cc", "value": [ { "Date": "2019-08-01T00:00:00-07:00", "TemperatureCelsius": 25, "Summary": "Hot", "Quantity": 45.88 } ] }
还有一段不完整的WeatherForecast类代码,我先帮你补全成能匹配JSON结构的完整类定义——因为你的JSON外层有@odata.context和value两个顶级字段,所以得额外定义一个根对象类来对应:
// 根对象类,匹配JSON的外层结构 public class WeatherForecastRoot { // 如果用.NET自带的System.Text.Json,用这个特性映射特殊字段名 [JsonPropertyName("@odata.context")] // 如果用Newtonsoft.Json(Json.NET),就换成下面这个 // [JsonProperty("@odata.context")] public string ODataContext { get; set; } // 对应JSON里的value数组 public List<WeatherForecast> Value { get; set; } } public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string Summary { get; set; } public double Quantity { get; set; } }
接下来给你两种常用的反序列化实现方式,你可以根据自己的项目情况选:
方式一:用.NET自带的System.Text.Json(无需额外安装包)
这是.NET Core及以后版本推荐的原生方案,不用装第三方包,直接用:
using System.Text.Json; using System.IO; using System.Linq; // 第一步:读取JSON文件的内容 string jsonFilePath = "你的JSON文件实际路径"; string jsonContent = File.ReadAllText(jsonFilePath); // 第二步:反序列化到我们定义的根对象类 var weatherForecastRoot = JsonSerializer.Deserialize<WeatherForecastRoot>(jsonContent); // 第三步:就可以正常访问数据啦,比如取第一个预报条目 if (weatherForecastRoot?.Value != null && weatherForecastRoot.Value.Any()) { WeatherForecast firstForecast = weatherForecastRoot.Value.First(); Console.WriteLine($"日期:{firstForecast.Date}"); Console.WriteLine($"温度:{firstForecast.TemperatureCelsius}℃"); Console.WriteLine($"天气总结:{firstForecast.Summary}"); Console.WriteLine($"数量:{firstForecast.Quantity}"); }
方式二:用Newtonsoft.Json(Json.NET,需安装NuGet包)
如果你的项目还在使用旧版.NET Framework,或者更习惯用Json.NET,那就先通过NuGet安装Newtonsoft.Json包,然后用下面的代码:
using Newtonsoft.Json; using System.IO; using System.Linq; // 读取JSON文件内容 string jsonFilePath = "你的JSON文件实际路径"; string jsonContent = File.ReadAllText(jsonFilePath); // 反序列化 var weatherForecastRoot = JsonConvert.DeserializeObject<WeatherForecastRoot>(jsonContent); // 访问数据 if (weatherForecastRoot?.Value != null && weatherForecastRoot.Value.Any()) { WeatherForecast firstForecast = weatherForecastRoot.Value.First(); Console.WriteLine($"日期:{firstForecast.Date}"); Console.WriteLine($"温度:{firstForecast.TemperatureCelsius}℃"); Console.WriteLine($"天气总结:{firstForecast.Summary}"); Console.WriteLine($"数量:{firstForecast.Quantity}"); }
最后提醒几个小要点:
- 类的属性类型一定要和JSON里的字段类型匹配,比如
Quantity是double,对应JSON里的45.88就没问题; - 如果属性名和JSON字段名不一样,一定要用特性(比如上面的
JsonPropertyName或JsonProperty)来做映射,不然反序列化会失败; - 如果你的JSON文件特别大,建议用流式反序列化来节省内存,但你的这个例子数据量小,直接读整个文件就够了。
备注:内容来源于stack exchange,提问作者69971 Inc
相关产品推荐
相关产品推荐

