JSON正在保存一个数据。
- 我需要移除节点;id";值与传入的值匹配。在下面的代码中,
var isRemoved = (dataDeserialized as JArray).Remove(index);
返回false。节点未被删除。如何删除节点 - 属性名称";id";甚至是动态的。它将被传入。我如何检查属性名称和值(当前(以查找索引
这是我迄今为止所拥有的:
var entityJson = @"
[
{
'id': 1,
'code': 'abc1'
},
{
'id': 2,
'code': 'abc2'
}
]".Replace("'", """);
var dataDeserialized = JsonConvert.DeserializeObject<dynamic>(entityJson);// DataLoader.DeserializeJson(entityJson, false);
if(dataDeserialized.Count > 0)
{
var key = "id";
var value = "2";
var index = 0;
var isFound = false;
foreach(var d in dataDeserialized)
{
if((string)d.id == value.ToString())
{
isFound = true;
break;
}
index++;
}
if (isFound)
{
var isRemoved = (dataDeserialized as JArray).Remove(index);
if (isRemoved)
{
var setting = new JsonSerializerSettings
{
DateParseHandling = DateParseHandling.None,
};
var resul = JsonConvert.SerializeObject(dataDeserialized, setting);
//var result = JsonHelper.SerializeObject(dataDeserialized);
}
}
}
我也尝试过jObject,但它给出了一个错误Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 2, position 13
dynamic obj = JObject.Parse(entityJson);
(obj.employees as JArray).RemoveAt(0);
更新#1:以下是对之上的#1有效的方法
if(dataDeserialized.Count > 0)
{
var key = "id";
var value = "2";
JArray list = new JArray();
foreach (var d in dataDeserialized)
{
if ((string)d.id != value.ToString())
{
list.Add(d);
}
}
if(list.Count > 0)
{
var result = JsonConvert.SerializeObject(list);
}
}
尽管如此,我怎么能做#2,检查";键";?
如果您不想将此json反序列化为强类型对象,我建议使用Newtonsoft.Json
包中的JObject
和JArray
类,因为它们在这方面更灵活。
因此,您可以使用以下动态密钥轻松地从json中删除节点:
string key = "id";
int id = 2;
var entityJson = @"
[
{
""id"": 1,
""code"": ""abc1""
},
{
""id"": 2,
""code"": ""abc2""
},
{
""id"": 3,
""code"": ""abc3""
}
]";
JArray jarray = JArray.Parse(entityJson);
var item = jarray.Children().Where(i => (int)(i as JObject).GetValue(key) == id).SingleOrDefault();
if (item != null)
{
jarray.Remove(item);
}
var resul = JsonConvert.SerializeObject(jarray);