问题
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