Search code examples
c#arraysjsonjson.net

Cannot access a jObject token in c#


I have the following json called 'originalJson'

{  
  "user_active": true,
  "user_firstname": "Bob",
  "user_lastname": "Tester",
  "user_displayname": "Bobby",
  "user_primary_email": "[email protected]",
  "user_login_enabled": true,
  "user_profile": {
       "user_locale": "en-gb",
       "user_lang": "en-gb"
   },
   "user_identities": [],
   "user_roles": [
   {
        "app_id": "74a019c9-7171-4af0-a773-3984edaa35ca",
        "context_uuid": "74a019c9-7171-4af0-a773-3984edaa35ca",
        "context_type": "context_application",
        "role_oid": "test_role_a",
        "role_start_date": "2020-06-27T13:00:00Z",
        "role_end_date": "2021-06-27T13:00:00Z"
    }
  ]
 }

and I am trying to replace the role_start_date and role_end_date values.

I have tried the following

JObject jObj = JObject.Parse(originalJson);

jObj["user_roles"]["role_start_date"] = somenewstartDate;
jObj["user_roles"]["role_end_date"] = somenewendDate;

However it is failing and doesn't like the "jObj["user_roles"]["role_start_date"]". I thought it would be pretty simple to do, I must be missing something.

Any ideas?


Solution

  • The property "user_roles" is an array of objects not a single object. You are trying to set a property value in the first entry in that array, so you need to do:

    jObj["user_roles"][0]["role_start_date"] = somenewstartDate;
    jObj["user_roles"][0]["role_end_date"] = somenewendDate;