Update json value using Newtonsoft library C#

We recently had a scenario where we needed to update the empty json array key questions with items having certain json key-value pairs containing user information.

Sample below shows part of the json to be updated:

"screens": [
                {
                  "uid": "<guid>",
                  "body": {
                    "text": "...",
                    "questions": []
                  }
			  }
		  ]

After update:

"screens": [
                {
                  "uid": "<guid>",
                  "body": {
                    "text": "...",
                    "questions": [
                      {
                        "uid": "another guid",
                        "name": "1st name",
                        .... other items
                      },
                      {
                        "uid": "another guid",
                        "name": "2nd name",
                        .... other items
                      }
                    ]
                  }
		}
	]

Below is the sample code that first removes the empty questions array and then adds it back after filling in the User information:

foreach (JToken token in jScreenItem["body"].Children())
{
	JProperty p = token as JProperty;
	if (p != null && p.Name.Contains("questions"))
	{
		token.Remove();
		break; //breaking when empty questions array is removed.
	}
}
foreach (JToken token in jScreenItem["body"].Children())
{
	JProperty p = token as JProperty;
	if (p != null && p.Name.Contains("text"))
	{
		JProperty jquestions = new JProperty("questions", JArray.FromObject(jUsers));
		token.AddAfterSelf(jquestions);
		break; //breaking when filled questions array is added.
	}
}

jUsers above is an array of Objects containing user information.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.