I want to deserialize a JSON string that I don't know its Type to an object of type Object
and be able to access its properties using reflection. when I used this
object myObject = JsonConvert.DeserializeObject("{\'Id\':\'1\'}");
the type of myObject
is of type JObject
and I am not able to access its properties using reflection.
is there a way to do so using Json.net or any other JSON deserializer?
I think you can deserialize the object into either a Dictionary<string,string>
or an expandoobject
(also castable to IDictionary<string,object>
) and then you don't need to use reflection to get at the properties, you can get them through the dictionary.
See: Deserialize Dynamic Json string using Newtonsoft JSON.NET
This doesn't let you use reflection per-se but an ExpandoObject does let you iterate over the properties:
string json = "{\'Id\':\'1\'}";
var converter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, converter);
IDictionary<string, object> dict = (IDictionary<string, object>)obj;
foreach (string key in dict.Keys)
{
Console.WriteLine(key);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.