如何反序列化结构不固定的泛型JSON并提取所有属性值
解决方案
你可以直接将JSON反序列化为 Newtonsoft.Json 提供的 JArray 类型,无需提前知道属性键名,通过遍历对象属性即可提取所有值,具体实现如下:
实现代码
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Collections.Generic; // result 为API返回的JSON字符串 var jArray = JsonConvert.DeserializeObject<JArray>(result); // 仅需要提取所有值的场景 List<object> allValues = new List<object>(); // 需要保留键值对映射的场景 List<KeyValuePair<string, object>> keyValuePairs = new List<KeyValuePair<string, object>>(); // 遍历数组内的每个JSON对象 foreach (JObject obj in jArray) { // 遍历对象的所有属性 foreach (JProperty prop in obj.Properties()) { allValues.Add(prop.Value); keyValuePairs.Add(new KeyValuePair<string, object>(prop.Name, prop.Value)); } }
其他说明
如果你的项目使用的是.NET 自带的 System.Text.Json 序列化库,可以用以下方案实现:
using System.Text.Json; using System.Collections.Generic; JsonElement jsonRoot = JsonSerializer.Deserialize<JsonElement>(result); List<object> allValues = new List<object>(); if (jsonRoot.ValueKind == JsonValueKind.Array) { foreach (JsonElement obj in jsonRoot.EnumerateArray()) { if (obj.ValueKind == JsonValueKind.Object) { foreach (JsonProperty prop in obj.EnumerateObject()) { allValues.Add(prop.Value); } } } }
之前使用 dynamic 无法访问的原因是动态类型依然需要明确键名才能取值,直接通过序列化框架提供的JSON结构对象遍历属性,是处理结构不固定JSON的通用方案。
内容的提问来源于stack exchange,提问作者Davide Di Giovanni
相关产品推荐
相关产品推荐

