且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用json.net获取所有字段?

更新时间:2023-01-17 20:57:40

您可以在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);
        }
    }
}