我正在尝试找到一种解决方案,以检查以下所示JSON中对象“ key6”的存在:
{
"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
}
}
如果JSON中的键不存在,我想向我的JObject添加一个新的Object,其名称为Object,其中包含一个键值对,如下所示:
//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));
}
}
如果键确实存在,则只需在现有对象中添加一个键值对。
有人对如何实现这一目标有建议吗?上面的代码显示以下错误:
更新:
我写了一些部分起作用的代码:
//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);
}
}
}
上面的代码中的“ if-condition”工作正常,当不存在名称为“ key6”的对象时,将添加该对象和该对象中的键值对,并设置布尔值“ objectExists”真实。当检测到同一对象(键)中存在另一个键值对时,我需要将其添加到已存在的“ key6”对象中,而不是创建一个新对象,这就是我在“其他-条件”。但这是行不通的,有人建议如何向现有Jproperty中添加键值对吗?
完成“ if-condition”后的属性如下:
在“ key6”中,我要添加键“ nameOther”之外的另一个键值对,其值是“ www.microsoft0nline.nl/test.php”。
答案 0 :(得分:0)
您可以尝试使用“ ContainsKey”方法来查找特定键对象的存在。希望下面的示例可以为您提供帮助
//Base JObject
JObject obj = new JObject();
obj["key1"] = "www.microsoft0nline.nl/test.php";
obj["key2"]= "2019-06-05 11:21:09";
obj["key3"] = "otherValue1";
//create JObject to add into my base JObject
JObject otherObj = new JObject();
string objectName = "key2";
otherObj.Add(new JProperty(objectName, "valuehelloworld"));
if(obj.ContainsKey(objectName))
{
objectExists = true;
}
else{
obj.Add(new JProperty(objectName, otherObj));
}