1

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!

ISquared
  • 364
  • 4
  • 22

1 Answers1

2

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();
Magnetron
  • 7,495
  • 1
  • 25
  • 41
  • Thank you for your input. The Odata is still an Object that doesn't have a GetProperty() method associated with it. I see JsonElement should have TryGetProperty and GetProperty() methods, but neither of them seem to work. – ISquared Feb 14 '23 at 13:28
  • @Isquare1 Have you declared Odata as `object`? Because by your code (the return of `GetType`), it is in fact a `JsonElement`, so you just have to cast it, like `((JsonElement)Odata).GetProperty("someProp").GetString();` – Magnetron Feb 14 '23 at 13:30
  • 1
    Casting the object to JsonElement worked, thank you infinite number of times! I set your answer as the accepted one :) – ISquared Feb 14 '23 at 13:37