How do I get all the fields using json.net?

偶尔善良 提交于 2021-01-29 04:55:39

问题


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

回答1:


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

Try it online: 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]);
        }
    }
}

Edit:

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



回答2:


This is what I had used in my project to get fields and values of a class:

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

Note that the reason I was checking !property.PropertyType.Namespace.StartsWith("System.Collections.Generic") as It was causing infinte loops in entity models and if that is not the case you can remove the if condition.



来源:https://stackoverflow.com/questions/40632398/how-do-i-get-all-the-fields-using-json-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!