如何仅将部分属性解析为JSON对象?(附C#示例)
可以直接将部分属性解析为JSON对象(无需字符串转换)
当然可以实现,完全不需要把JSON属性转成字符串再处理。你的类定义本身就适配了这种动态属性的场景,直接用Newtonsoft.Json(Json.NET)就能完成序列化和反序列化操作。
反序列化示例(JSON字符串转Request对象)
using Newtonsoft.Json; using Newtonsoft.Json.Linq; string jsonInput = @" { ""Title"":""My title"", ""Address"":{ ""property1"":1, ""property2"":2 }, ""Addresses"":[ { ""property1"":1, ""property2"":2 }, { ""property1"":1, ""property2"":2 } ] }"; Request request = JsonConvert.DeserializeObject<Request>(jsonInput); // 访问Address的动态属性 int addressProp1 = (int)request.Address["property1"]; // 遍历Addresses列表中的动态对象 foreach (JObject addr in request.Addresses) { int addrProp2 = (int)addr["property2"]; }
序列化示例(Request对象转JSON字符串)
Request request = new Request { Title = "My title", Address = new JObject { ["property1"] = 1, ["property2"] = 2 }, Addresses = new List<JObject> { new JObject { ["property1"] = 1, ["property2"] = 2 }, new JObject { ["property1"] = 1, ["property2"] = 2 } } }; string jsonOutput = JsonConvert.SerializeObject(request, Formatting.Indented);
原理说明
Newtonsoft.Json原生支持JObject(对应JSON对象)和JArray(对应JSON数组,可映射为List<JObject>)与JSON结构的直接映射,序列化/反序列化时会自动处理这些动态属性,不需要额外的字符串转换步骤。
内容的提问来源于stack exchange,提问作者akshay_zz
相关产品推荐
相关产品推荐

