[英]Getting property from c# anonymous object
On a server, I get JSON objects.在服务器上,我得到 JSON 对象。 I use JsonConvert to deserialize them into anonymous objects.
我使用 JsonConvert 将它们反序列化为匿名对象。 I then want to access the members, but I can't do something like:
然后我想访问成员,但我不能做这样的事情:
object a = jsonObj.something.something.else;
So I created the following, with the intention of being able to access a member using an array of selector strings.所以我创建了以下内容,目的是能够使用选择器字符串数组访问成员。 However, getProperty() here always returns null.
但是,这里的 getProperty() 总是返回 null。 Any ideas?
有任何想法吗?
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
does not deserialize to anonymous object (I guess, you don't use JsonConvert.DeserializeAnonymousType ). JsonConvert.DeserializeObject
不会反序列化为匿名对象(我猜,你不使用JsonConvert.DeserializeAnonymousType )。 Depending on json it returns either JObject
or JArray
.根据 json,它返回
JObject
或JArray
。
1. Since JObject implements IDictionary<string, JToken>
you can use it this way 1.由于JObject实现了
IDictionary<string, JToken>
你可以这样使用
string json = @"{prop1:{prop2:""abc""}}";
JObject jsonObj = JsonConvert.DeserializeObject(json) as JObject;
Console.WriteLine(jsonObj["prop1"]["prop2"]);
or或者
string str = (string)jsonObj.SelectToken("prop1.prop2");
2. If you want to use the dynamic keyword, then 2.如果要使用dynamic关键字,那么
dynamic jsonObj = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonObj.prop1.prop2);
Both ways will print abc
两种方式都会打印
abc
my code我的代码
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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.