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

时间:2016-11-16 12:38:40

标签: c# json json.net

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

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

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")的原因是因为它在实体模型中导致了infinte循环,如果不是这样,你可以删除if条件。

相关问题