问题描述
在服务器上,我得到JSON对象。我使用JsonConvert将其反序列化为匿名对象。然后,我要访问的成员,但我不能做这样的事情:
对象= jsonObj.something.something.else;
所以,我创建了以下,具有能够访问使用选择字符串数组成员的意图。然而,的getProperty()这里总是返回null。任何想法?
私有对象recGetProperty(对象currentNode,字符串[]选择,诠释指数){
尝试{
类型节点类型= currentNode.GetType();
反对nextNode = nodeType.GetProperty(选择[指数]);
如果(指数==(selectors.Length - 1)){
返回nextNode;
}
其他{
返回recGetProperty(nextNode,选择器,索引+ 1);
}
}
赶上(例外五){
返回null;
}
}私有对象的getProperty(对象根,字符串[]选择器){
返回recGetProperty(根,选择器0);
}
JsonConvert.DeserializeObject
不反序列化到匿名对象(我猜,你不使用的 JsonConvert.DeserializeAnonymousType 的)。根据JSON它返回要么 JObject
或 JArray
。
1 由于 JObject 的器具的IDictionary<字符串,JToken>
你可以使用这种方式。
JSON字符串= @{为prop1:{prop2:ABC}};JObject jsonObj = JsonConvert.DeserializeObject(JSON)作为JObject;
Console.WriteLine(jsonObj [为prop1] [prop2]);
或
字符串str =(字符串)jsonObj.SelectToken(prop1.prop2);
2 如果您想使用的动态的关键字,然后
动态jsonObj = JsonConvert.DeserializeObject(JSON);
Console.WriteLine(jsonObj.prop1.prop2);
这两种方法将打印 ABC
On a server, I get JSON objects. I use JsonConvert to deserialize them into anonymous objects. 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. 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). Depending on json it returns either JObject
or JArray
.
1. Since JObject implements IDictionary<string, JToken>
you can use it this way
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
dynamic jsonObj = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonObj.prop1.prop2);
Both ways will print abc
这篇关于获取财产从C#匿名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!