Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

using dynamic type in C# and accessing elements array from JSON (dynamic type and DynamicJsonObject)

i have a json string taken from a 3rd party API.
however this third party API, we dont know the exact JSON definitions of it and has a lot of attribute, we just know that they have the information that we need on it

here is an example

{
  "exp": 1670979934,
  "iat": 1670979634,
  "auth_time": 1670979634,
  "jti": "86a4610c-9e9a-473f-9cc0-0959aa779702",
  "iss": "http://localhost:8080/auth/realms/ScopicSoftware",
  "aud": "account",
  "sub": "2874bbca-e34b-44f0-8ca7-cfc57708a124",
  "typ": "Bearer",
  "azp": "keycloakdemo",
  "realm_access": {
    "roles": [
      "default-roles-scopicsoftware",
      "offline_access",
      "uma_authorization"
    ]
  },
  "resource_access": {
    "keycloakdemo": {
      "roles": [
        "admin"
      ]
    },
    "account": {
      "roles": [
        "manage-account",
        "manage-account-links",
        "view-profile"
      ]
    }
  }
...
...
}

as I said we dont own and dont have the exact information of the JSON except for the output, so we cannot just do Json.Deserialize and pass a model object to it. (or can we based on limited info?)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

we want to acccess the "resource_access"->"keycloak_demo" and the "roles" array

what i tried was to use the dynamic type in C# instead

dynamic dataX = Json.Decode(responseString);

and i can access the information thru

   var demo = dataX.resource_access.keycloakdemo;

it returns an a variable with type DynamicJsonArray.
However, i cannot iterate to it using ordinary for loop or Enumerator, it crashes.

So what is the proper way of doing this given We dont have the model definition?

>Solution :

you can use code like this

var jsonParsed = JObject.Parse(json);

string[] roles = jsonParsed.SelectToken("resource_access.keycloakdemo.roles")
                                                          .ToObject<string[]>();

foreach (string role in roles)
{

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading