如何使用json.net获取所有字段? [英] How do I get all the fields using json.net?

查看:66
本文介绍了如何使用json.net获取所有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第三方正在给我类似以下内容.当我知道键(例如easyField)时,获取值很容易.下面我在控制台中编写它.但是,第三方给了我使用随机密钥的json.如何访问?

A third party is giving me something similar to the below. When I know the key (such as easyField) getting the value is easy. Below I write it in the console. However the third party gave me json that uses random keys. How do I access it?

{
    var r = new Random();
    dynamic j = JsonConvert.DeserializeObject(string.Format(@"{{""{0}"":""hard"", ""easyField"":""yes""}}", r.Next()));
    Console.WriteLine("{0}", j["easyField"]);
    return;
}

推荐答案

您可以在JSON.NET中使用反射!它将为您提供字段的键.

You can use reflection with JSON.NET! It will give you the keys of your fields.

在线尝试:演示

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


public class Program
{
    public IEnumerable<string> GetPropertyKeysForDynamic(dynamic jObject)
    {
        return jObject.ToObject<Dictionary<string, object>>().Keys;
    }

    public void Main()
    {
        var r = new Random();
        dynamic j = JsonConvert.DeserializeObject(string.Format(@"{{""{0}"":""hard"", ""easyField"":""yes""}}", r.Next()));

        foreach(string property in GetPropertyKeysForDynamic(j))
        {
            Console.WriteLine(property);
            Console.WriteLine(j[property]);
        }
    }
}

一个更简单的解决方案:

An even simpler solution:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Program
{
    public void Main()
    {
        var r = new Random();
        dynamic j = JsonConvert.DeserializeObject(string.Format(@"{{""{0}"":""hard"", ""easyField"":""yes""}}", r.Next()));

        foreach(var property in j.ToObject<Dictionary<string, object>>())
        {
            Console.WriteLine(property.Key + " " + property.Value);
        }
    }
}

这篇关于如何使用json.net获取所有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆