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

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

转载于:https://my.oschina.net/dongri/blog/761285

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值