我如何得到所有的字段使用json.net

本文关键字:字段 json net 何得 | 更新日期: 2023-09-27 18:18:24

第三方给了我类似下面的东西。当我知道键(如easyField)时,获得值很容易。下面我把它写在控制台中。然而,第三方给了我使用随机密钥的json。我如何访问它?

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

我如何得到所有的字段使用json.net

你可以在JSON.NET中使用反射!它会给你字段的键。

在线试用:Demo

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]);
        }
    }
}
<标题>编辑:

一个更简单的解决方案:

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

这是我在项目中用来获取类的字段和值的方法:

public static List<KeyValuePair> ClassToList(this object o)
{
    Type type = o.GetType();
    List<KeyValuePair> vals = new List<KeyValuePair>();
    foreach (PropertyInfo property in type.GetProperties())
    {
        if (!property.PropertyType.Namespace.StartsWith("System.Collections.Generic"))
        {
              vals.Add(new KeyValuePair(property.Name,(property.GetValue(o, null) == null ? "" : property.GetValue(o, null).ToString()))
        }
    }
    return sb.ToString();
}

请注意,我检查!property.PropertyType.Namespace.StartsWith("System.Collections.Generic")的原因是它在实体模型中引起无限循环,如果不是这种情况,您可以删除if条件。