0

I am using httpClient to an API endpoint. There are a couple of possible JSON results I could get back depending on if the call if successful or not.

So I want to use a dynamic or ExpandoObject to DeserializeObject the results to.

However, I can't seem to be able to actual get anything from the object after Deserializing. I keep getting `

error CS1061: 'object' does not contain a definition for 'success' and no accessible extension method 'success' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)'

Here is a simplified example:

dynamic stuff = JsonConvert.DeserializeObject<ExpandoObject>("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

When I try to access name like this stuff.name I get the following error:

error CS1061: 'object' does not contain a definition for 'name' and no accessible extension method 'name' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) ? stuff["name"] error CS0021: Cannot apply indexing with [] to an expression of type 'object'

And yet the data is in there somewhere:

enter image description here

If I Deserialize like this I get the exact same result:

dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

It was inferred in another post that it may have something to do with this being in an async function, but no real solution. I am running .Net core 3.1 from within an Azure function.

So how do I refer to the object to get a value out?

8
  • 2
    are the property names case sensitive? You have stuff.name, but the key is Name Commented Aug 11, 2021 at 0:08
  • 2
    The property name is Name not name -- capitalization matters. Anyway ExpandoObject implements IDictionary<String,Object> so you can loop though or search for members that way, see How to dynamically get a property by name from a C# ExpandoObject?. Commented Aug 11, 2021 at 0:08
  • Oops. Made a mistake on this test data. But no difference. Still get the error. Commented Aug 11, 2021 at 0:25
  • @dbc, Ok that worked: var byName = (IDictionary<string, object>)stuff; string val = (string)byName["Name"]; and for nested objects: var address = (IDictionary<string, object>)stuff.Address; string city = (string)address["City"]; Pretty clumsy, but works. Commented Aug 11, 2021 at 0:38
  • stuff.Name works also, see dotnetfiddle.net/wA9SXA. Not sure where your problem is. Commented Aug 11, 2021 at 1:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.