C#获取动态key的json对象的值

C#获取动态key的json对象的值

问题描述

若是直接获取某个json数组中的元素将获得以下的jsonjson

{
    "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就能序列化了,以下。app

{
    "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那部分,能够反序列化的字符串,请使用以下的函数,注意引入类库。code

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
/// <summary>
/// 本类用于处理动态Key的json对象
/// </summary>
/// <param name="jObject">须要处理的json对象</param>
/// <returns>json对象的第一个元素的values</returns>
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;
}
相关文章
相关标签/搜索