从c#匿名对象获取属性
在服务器上,我获取JSON对象。我使用JsonConvert将它们反序列化为匿名对象。然后我想访问成员,但无法执行以下操作:从c#匿名对象获取属性,c#,asp.net,json,recursion,anonymous-types,C#,Asp.net,Json,Recursion,Anonymous Types,在服务器上,我获取JSON对象。我使用JsonConvert将它们反序列化为匿名对象。然后我想访问成员,但无法执行以下操作: object a = jsonObj.something.something.else; 因此,我创建了以下内容,目的是能够使用选择器字符串数组访问成员。但是,这里的getProperty()总是返回null。有什么想法吗 private object recGetProperty(object currentNode, string[] selectors, int
object a = jsonObj.something.something.else;
因此,我创建了以下内容,目的是能够使用选择器字符串数组访问成员。但是,这里的getProperty()总是返回null。有什么想法吗
private object recGetProperty(object currentNode, string[] selectors, int index) {
try {
Type nodeType = currentNode.GetType();
object nextNode = nodeType.GetProperty(selectors[index]);
if (index == (selectors.Length - 1)) {
return nextNode;
}
else {
return recGetProperty(nextNode, selectors, index + 1);
}
}
catch (Exception e) {
return null;
}
}
private object getProperty(object root, string[] selectors) {
return recGetProperty(root, selectors, 0);
}
JsonConvert.DeserializeObject
不会反序列化为匿名对象(我想,您不会使用JsonConvert.DeserializeAnonymousType)。根据json,它返回JObject
或JArray
1.由于JObject实现了IDictionary
,因此可以这样使用它
string json = @"{prop1:{prop2:""abc""}}";
JObject jsonObj = JsonConvert.DeserializeObject(json) as JObject;
Console.WriteLine(jsonObj["prop1"]["prop2"]);
或
2.如果要使用动态关键字,则
dynamic jsonObj = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonObj.prop1.prop2);
两种方式都将打印我的代码
Dictionary<string, object> dictionaryObject = new Dictionary<string, object>();
if (anonymousObject is string)
{
dictionaryObject = JsonConvert.DeserializeObject<Dictionary<string,object>>((string)anonymousObject);
}
if (!dictionaryObject.ContainsKey(propertyName))
{
throw new Exception($"property name '{propertyName}' not found");
}
object value = dictionaryObject[propertyName];
Dictionary dictionaryObject=new Dictionary();
if(匿名对象为字符串)
{
dictionaryObject=JsonConvert.DeserializeObject((字符串)anonymousObject);
}
如果(!dictionaryObject.ContainsKey(propertyName))
{
抛出新异常($“未找到属性名“{propertyName}”);
}
对象值=dictionaryObject[propertyName];
但是你不能做这样的事情:…
为什么?你试过使用dynamic关键字吗?你可以使用dynamics。看,我对c#还不熟悉。我还没听说过这个。dynamic允许使用“.”符号进行访问,但这可以用于使用一系列字符串进行访问吗?字符串索引在动态类型对象上似乎不起作用。
Dictionary<string, object> dictionaryObject = new Dictionary<string, object>();
if (anonymousObject is string)
{
dictionaryObject = JsonConvert.DeserializeObject<Dictionary<string,object>>((string)anonymousObject);
}
if (!dictionaryObject.ContainsKey(propertyName))
{
throw new Exception($"property name '{propertyName}' not found");
}
object value = dictionaryObject[propertyName];