gpt4 book ai didi

c# - 从 C# 匿名对象获取属性

转载 作者:行者123 更新时间:2023-11-30 14:55:22 25 4
gpt4 key购买 nike

在服务器上,我得到 JSON 对象。我使用 JsonConvert 将它们反序列化为匿名对象。然后我想访问成员,但我不能做类似的事情:

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,它返回 JObjectJArray .

1. 由于 JObject 实现了 IDictionary<string, JToken>你可以这样使用它

string json = @"{prop1:{prop2:""abc""}}";

JObject jsonObj = JsonConvert.DeserializeObject(json) as JObject;
Console.WriteLine(jsonObj["prop1"]["prop2"]);

string str = (string)jsonObj.SelectToken("prop1.prop2");

2.如果你想使用dynamic关键字,那么

dynamic jsonObj = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonObj.prop1.prop2);

两种方式都会打印abc

关于c# - 从 C# 匿名对象获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25431204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com