I'm trying to find a solution to check the existence of Object "key6" in the JSON shown below:
{
"key1": "www.microsoft0nline.nl/test.php",
"key2": "2019-06-05 11:21:09",
"key3": "otherValue1",
"key4": "433",
"key5": [
"35",
"37",
"43"
],
"key6": {
"nameOther: "object123456",
"descriptionOther": "A object type123456",
"sizeOther": 120123456
}
}
If the key in the JSON does not exist, I want to add a new Object to my JObject with the name of the Object and a key-value pair within, like this:
//Base JObject
JObject obj = new JObject();
//create JObject to add into my base JObject
JObject otherObj = new JObject();
otherObj.Add(new JProperty(keyOfObject, property.Value));
//check if property does not already exists
foreach (JProperty property1 in obj.Properties().ToList()) //check if object already exists
{
if (objectName.Equals(property1.Name)) //Exists
{
property1.Add(otherObj);
}
else
{
obj.Add(new JProperty(objectName, otherObj));
}
}
If the key does exist, it will just need to add a key-value pair into the existing object.
Does anyone have suggestions about how to achieve this? The code above shows the following error:
UPDATE:
I've written some code that partly works:
//check if property does not already exists
if (objectExists == false && property.Name.Equals(item.KeyOther))
{
obj.Add(new JProperty(objectName, otherObj));
objectExists = true;
} else if (objectExists == true && property.Name.Equals(item.KeyOther))
{
foreach (JProperty property1 in obj.Properties().ToList()) //check if object already exists
{
if (property1.Name.Equals(objectName))
{
property1.Add(otherObj);
}
}
}
The "if-condition" in the code above works fine, when there is not a object with the name "key6" the object and the key-value pair within this object are added, also the boolean "objectExists" is set to true. When there is another key-value pair within the same object(key) detected I need to add this to the already existing "key6" object instead of creating a new object, this is what I'm trying to do in the "else-condition". However this does not work, does anyone have suggestions how to add a key-value pair to an existing Jproperty?
The property after finishing the "if-condition" looks as this:
Within the "key6" I want to add another key-value pair besides key "nameOther" with its value "www.microsoft0nline.nl/test.php".