C#对象 – 从对象内的JSON中获取属性

huangapple go评论51阅读模式
英文:

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:

{ &quot;someProp&quot; : &quot;someValue&quot;,
&quot;anotherProp&quot; : &quot;anotherValue&quot; .. } 

=> 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(&quot;someProp&quot;).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(&quot;someProp&quot;).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(&quot;someProp&quot;).GetString();

huangapple
  • 本文由 发表于 2023年2月14日 20:58:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定