关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

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

发布时间:2020-02-04 17:42:32

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;

/// <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;

}



/template/Home/Zkeys/PC/Static