英文:
C# Object - get properties from json within the object
问题
我的HTTP响应数据包括一个结构化为Dictionary<string, object>的字段。在调试模式中访问该对象时,显示了我期望看到的内容,即:
ValueKind = Object:
{ "someProp" : "someValue",
"anotherProp" : "anotherValue" .. }
=> 因此,该对象包含了我需要访问的大型JSON格式数据。然而,我无法弄清楚如何实现这一点。通常建议的方法返回null:
var myValue = Odata.GetType().GetProperty("someProp").GetValue(Odata, null);
这让我认为应该进行一些序列化,但无论我尝试多少次,都找不到任何有效的方法。
以下是更多信息,如果不够,我会添加所需的内容。我将其分解成很多步骤,以尽量清晰地展示我每一步得到的内容:
// 假设Odata = 字典中的对象值
// 执行反射
var type = Odata.GetType() // 这会得到System.Text.json.JsonElement
// 在运行时获取类型属性
var props = type.GetProperties()
// 返回长度为2的数组:System.Text.Json.ValueKind和System.Text.Json.JsonElement
// 尝试在JsonElement中访问我的属性
var someValue= type.GetProperty("someProp").GetValue(Odata, null) // 这会返回null
我不一定需要一个确切的解决方案,但指导我阅读的正确位置也将非常有用!
英文:
My HTTP response data includes a field that is structured as a Dictionary<string,object>. Accessing the Object in debug mode shows me what I expect to see, i.e.
ValueKind = Object:
{ "someProp" : "someValue",
"anotherProp" : "anotherValue" .. }
=> the object therefore contains the large json formatted data that I need to access. However, I can't figure out how to do that .. The commonly suggested method returns null:
var myValue = Odata.GetType().GetProperty("someProp").GetValue(Odata, null);
which makes me think there is something I should be serializing which I am not and regardless how much I tried, I can't find any methods to work.
Here is some more info, if it is not enough I will add whatever is needed. I broke it down a lot to try to show clearly what I am getting each step):
// assume Odata = the Object value from the dictionary
//perform reflection
var type = Odata.GetType() // this gives System.Text.json.JsonElement
//get type properties at runtime
var props = type.GetProperties()
//returns array of 2 :
//System.Text.Json.ValueKind and System.Text.json.JsonElement
//attempting to access my properties in the JsonElement
var someValue= type.GetProperty("someProp").GetValue(Odata,null) //this gives null
I don't necessarily want an exact solution, but pointing me to the right place to read would also be very useful!
答案1
得分: 2
当你使用 GetType().GetProperty()
时,你正在使用 Type
类的 GetProperty()
方法,这涉及到反射。你应该使用 JsonElement
类的 GetProperty
方法代替:
var myValue = Odata.GetProperty("someProp").GetString();
英文:
When you do GetType().GetProperty()
you're using the GetProperty()
method from Type
class, you're using reflection. You want to use the GetProperty
method of JsonElement
class instead:
var myValue = Odata.GetProperty("someProp").GetString();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论