一尘不染

从JSON对象中删除特定属性

json

我有一个JSON:

{
    "scbs_currentstatus": "",
      "scbs_primaryissue": "",
      "_umb_id": "Test",
      "_umb_creator": "Admin",
      "_umb_createdate": "0001-01-01 00:00:00",
      "_umb_updatedate": "0001-01-01 00:00:00",
      "_umb_doctype": "Test",
      "_umb_login": "Test",
      "_umb_email": "Test",
      "_umb_password": {
        "newPassword": "Test",
        "oldPassword": null,
        "reset": null,
        "answer": null
      },
      "_umb_membergroup": {
        " User": false,
        "Line User": true,
        "Callback User": false,
        "Su User": false,
        },
      "umbracoMemberComments": "Test",
      "umbracoMemberFailedPasswordAttempts": ""

    }

我试图删除所有以 “ umb_” 开头的属性。这在json.net中可能吗?

输出将是这样的:

{
        "scbs_currentstatus": "",
          "scbs_primaryissue": "",
           "umbracoMemberComments": "Test",
          "umbracoMemberFailedPasswordAttempts": ""
}

使用删除我能够做到,但是不能一次全部完成。

   result.Property("_umb_id").Remove();

有什么建议吗?


阅读 472

收藏
2020-07-27

共1个答案

一尘不染

您可以先解析字符串:

var temp =  JArray.Parse(json);
temp.Descendants()
    .OfType<JProperty>()
    .Where(attr => attr.Name.StartsWith("_umb_"))
    .ToList() // you should call ToList because you're about to changing the result, which is not possible if it is IEnumerable
    .ForEach(attr => attr.Remove()); // removing unwanted attributes
json = temp.ToString(); // backing result to json

更新 或:

result.Properties()
    .Where(attr => attr.Name.StartsWith("_umb_"))
    .ToList()
    .ForEach(attr => attr.Remove());

更新#2

您可以在where子句中指定更多条件:

.Where(attr => attr.Name.StartsWith("_umb_") && some_other_condition)

要么

.Where(attr => attr.Name.StartsWith("_umb_") || some_other_condition)

或任何您需要的。

2020-07-27