Remove specific properties from JSON object

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

I have a JSON:

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


        
2条回答
  •  暗喜
    暗喜 (楼主)
    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 removeList = new List();
    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();
    }
    }
    

提交回复
热议问题