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?
CodePudding user response:
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)
{
}