C#获取动态key的json对象的值
问题描述
如果直接获取某个json数组中的元素将得到如下的json
{ "44": { "height": 25, "appeared": -70000000, "length": 44, "order": "saurischia", "vanished": -70000000, "weight": 135000 }}
这个json对象如果使用C#类来反序列化,那么实体类的结构如下,实体类的类名需要与json对象key相同的才可以使用json反序列化,这样对程序造成了极大的不便。
public class 44{ public int height { get; set; } public int appeared { get; set; } public int length { get; set; } public string order { get; set; } public int vanished { get; set; } public int weight { get; set; }}public class Root{ public 44 44 { get; set; }}
解决方案
以上json对象由于key是动态的无法使用C#反序列化,但是直接取到value就能序列化了,如下。
{ "height":25, "appeared":-70000000, "length":44, "order":"saurischia", "vanished":-70000000, "weight":135000}
以上json对象就可以使用我们常用的格式转换了。
public class Root{ public int height { get; set; } public int appeared { get; set; } public int length { get; set; } public string order { get; set; } public int vanished { get; set; } public int weight { get; set; }}
实现代码
从动态key的json对象里面拿到value那部分,可以反序列化的字符串,请使用如下的函数,注意引入类库。
using Newtonsoft.Json;using Newtonsoft.Json.Linq;using System.Linq;
////// 本类用于处理动态Key的json对象/// /// 需要处理的json对象///json对象的第一个元素的values public static string GetJsonValue(string strJson){ string strResult; JObject jo = JObject.Parse(strJson); string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray(); if (values == null) { strResult = ""; } else { strResult = values[0]; } return strResult;}