问题
I have JSON object, something like this, and its dynamic, jsonInput=
{
"CONTRATE":80,
"SALINC":30,
"RETAGE":67,
"MARSTATUS":"single",
"SPOUSEDOB":"1970-01-01",
"VIEWOPTION":"pension"
}
I am converting it into .NET dynamic object using Newtonsoft.Json converter:
var jsonDynamic = JsonConvert.DeserializeObject<dynamic>(jsonInput);
Now I have dynamic jsonDynamic .NET object.
How can I get it's properties now? These should be jsonDynamic.CONTRATE, jsonDynamic.SALINC etc...
How can I get the names of these properties from jsonDynamic?
Thanks.
回答1:
You could create a class that would represent the json you want to deserialize, like below:
public class ClassName
{
public int Contrate { get; set; }
public int Salinc { get; set; }
// Here you will place the rest of your properties.
}
and then just use this:
var jsonDynamic = JsonConvert.DeserializeObject<ClassName>(jsonInput);
This way you will avoid making use of a dynamic object.
回答2:
var jobj = JObject.Parse(jsonInput);
dynamic jsonDynamic = jobj;
var dict = jobj.Children()
.OfType<JProperty>()
.ToDictionary(x => x.Name, x => x.Value);
int c = (int)dict["CONTRATE"];
or if you want only property names
var propNames = jobj.Children()
.OfType<JProperty>()
.Select(x => x.Name)
.ToList();
回答3:
You should deserialize into a Dictionary and then you can loop through the Keys to get the property names
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonInput);
You can access the values.Keys to get the property names then.
来源:https://stackoverflow.com/questions/29422322/how-to-get-a-list-of-dynamic-object-properties-in-c-sharp