1

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?)

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?

2
  • 1
    resource_access is an object not an array, it contains a property named keycloakdemo which contains an array named roles Commented Dec 14, 2022 at 2:18
  • 1
    To iterate dynamic type: iterate-over-an-array-of-dynamic-type-in-c-sharp Commented Dec 14, 2022 at 2:23

1 Answer 1

1

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)
{

}
Sign up to request clarification or add additional context in comments.

1 Comment

this one worked as well, thanks!

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.