从JSON对象中删除特定属性

时间:2016-03-29 07:04:46

标签: c# json c#-4.0 json.net

我有一个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": ""

    }

Iam尝试删除所有属性,首先是" umb _" 。这可能在json.net中吗?

并输出如下:

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

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

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

有什么建议吗?

2 个答案:

答案 0 :(得分:9)

您可以先解析字符串:

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)

OR

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

或者你需要什么。

答案 1 :(得分:-1)

我最终反序列化为JObject并递归循环以删除不需要的字段。这是感兴趣的人的功能。

private void removeFields(JToken token, string[] fields)
{
JContainer container = token as JContainer;
if (container == null) return;

List<JToken> removeList = new List<JToken>();
foreach (JToken el in container.Children())
{
    JProperty p = el as JProperty;
    string propertyName = p.hasOwnProperty(key);

    if (p != null && fields.Contains(p.propertyName) && p.propertyName.substring(0,4) == "_umb" )
    {
        removeList.Add(el);
    }
    removeFields(el, fields);
}

foreach (JToken el in removeList)
{
    el.Remove();
}
}