【问题标题】:How do I get all the fields using json.net?如何使用 json.net 获取所有字段?
【发布时间】:2016-11-17 04:16:22
【问题描述】:

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

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

【问题讨论】:

  • 你能提供一个关于dotnetfiddle的例子吗?
  • 感谢您的 mcve 顺便说一句。 :)

标签: c# json json.net


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    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 条件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-22
      • 2022-08-02
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多