Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

c# - Remove specific properties from JSON object

I have a 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 trying to remove all the properties start with "umb_" .is this possible in json.net?

and output will be like:

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

using remove i am able to to do it however not all at a time.

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

any suggestion please?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can parse the string first:

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

UPDATE OR:

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

UPDATE #2

You can specify more conditions in where clause:

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

OR

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

Or whatever you need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...