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.