从JSON删除节点并向上移动子级

时间:2019-03-28 09:12:52

标签: c# json json.net

我有一些JSON,想从JSON中删除一个节点,但将已删除节点内的节点移至其父节点。

这是我要开始使用的JSON:

{
    "Response": {
        "Outcome": {
            "KeyValueOfstringOutcomepQnxSKQu": [
                {
                    "Key": "Icon",
                    "Value": {
                        "DataType": "System.String",
                        "Field": "Icon",
                        "Value": "O"
                    }
                },
                {
                    "Key": "IconDescription",
                    "Value": {
                        "DataType": "System.String",
                        "Field": "IconDescription",
                        "Value": "Old"
                    }
                },
                {
                    "Key": "IconLongDescription",
                    "Value": {
                        "DataType": "System.String",
                        "Field": "IconLongDescription",
                        "Value": "Older"
                    }
                }
            ]
        }
    }
}

这是我要结束的JSON。我需要删除KeyValueOfstringOutcomepQnxSKQu节点,但其子节点仍必须存在于JSON中:

{
    "Response": {
        "Outcome": [
            {
                "Key": "Icon",
                "Value": {
                    "DataType": "System.String",
                    "Field": "Icon",
                    "Value": "O"
                }
            },
            {
                "Key": "IconDescription",
                "Value": {
                    "DataType": "System.String",
                    "Field": "IconDescription",
                    "Value": "Old"
                }
            },
            {
                "Key": "IconLongDescription",
                "Value": {
                    "DataType": "System.String",
                    "Field": "IconLongDescription",
                    "Value": "Older"
                }
            }
        ]
    }
}

我已经尝试过删除这样的节点,但是据我所知:

JObject rss = JObject.Parse(Convert.ToString(jsonText));

var x = rss.Remove("KeyValueOfstringOutcomepQnxSKQu");

我怎样才能使孩子们向上移动?

1 个答案:

答案 0 :(得分:0)

您可以使用SelectTokenReplace进行此操作:

JObject rss = JObject.Parse(jsonText);
rss.SelectToken("Response.Outcome")
   .Replace(rss.SelectToken("Response.Outcome.KeyValueOfstringOutcomepQnxSKQu"));
jsonText = rss.ToString();

提琴:https://dotnetfiddle.net/L6XoAf