当条件满足时,我一直在尝试将元素添加到JArrays 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();
答案 0 :(得分:1)
如果元素不存在,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();
答案 1 :(得分:0)
你能检查一下是否有效吗?
将rows[i].Children().ADD(@"""3"":""Three""");
更改为
rows[i].Children().Add(JToken.Parse(@"""3"":""Three"""));