Remove specific properties from JSON object

后端 未结 2 911
孤城傲影
孤城傲影 2020-12-10 09:33

I have a JSON:

{
    \"scbs_currentstatus\": \"\",
      \"scbs_primaryissue\": \"\",
      \"_umb_id\": \"Test\",
      \"_umb_creator\": \"Admin\",
      \         


        
相关标签:
2条回答
  • 2020-12-10 09:59

    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.

    0 讨论(0)
  • 2020-12-10 10:03

    I just ended up deserializing to JObject and recursively looping through that to remove unwanted fields. Here's the function for those interested.

    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();
    }
    }
    
    0 讨论(0)
提交回复
热议问题