我一直在尝试在满足条件时将元素添加到jarray JToken中。我想要实现的是如下所示。然而,下面的add语句没有编译,但传达了我需要尝试和执行的操作。有人知道怎么做吗?
string json = @"[
{""1"":""One"",""2"":""AddThree""},
{""1"":""One"",""2"":""Two""},
{""1"":""One"",""2"":""AddThree""}
]";
JArray rows = JArray.Parse(json);
int length = rows.Count;
for (int i = 0; i < length; i++)
{
string s = rows[i]["2"].ToString();
if (s == "AddThree")
{
//This functionality doesnt exist
rows[i].Children().ADD(@"""3"":""Three""");
}
}
Console.WriteLine(rows.ToString());
Console.ReadKey();
如果该元素不存在,Json将在设置该元素时创建该元素。
string json = @"[
{""1"":""One"",""2"":""AddThree""},
{""1"":""One"",""2"":""Two""},
{""1"":""One"",""2"":""AddThree""}
]";
JArray rows = JArray.Parse(json);
foreach (var row in rows)
{
string s = row["2"].ToString();
if (s == "AddThree")
{
row["3"] = "Three";
}
}
Console.WriteLine(rows.ToString());
Console.ReadKey();
你能检查一下这是否有效吗?
将rows[i].Children().ADD(@"""3"":""Three""");
更改为
rows[i].Children().Add(JToken.Parse(@"""3"":""Three"""));