0

I would like to remove properties based on a list of strings when serializing an object. I have tried to use DefaultContractResolver, but it provides property.PropertyName and nothing related to path or parent object:

public class Foo {
     public Bar Bar {get;set;}
}

public class Bar {
     public int MyProperty { get;set; }
     public int MyProperty2 { get;set; }
     public int MyProperty3 { get;set; }
}

var remove = new List<string> {
     "Foo.Bar.MyProperty"
}

What is the best approach to serialize that object in a manner that Foo.Bar.MyProperty will not be serialized?

MuriloKunze
  • 15,195
  • 17
  • 54
  • 82
  • no, I'm talking about json – MuriloKunze Nov 07 '18 at 21:31
  • This is explained here: https://stackoverflow.com/questions/25157511/newtonsoft-add-jsonignore-at-runtime – Reno Nov 07 '18 at 21:35
  • That class only provides "p.PropertyName", it does not provide any information about path (like Foo.Bar) or parent object, so I can't use. – MuriloKunze Nov 07 '18 at 21:37
  • 1
    Not really possible currently, see [How to perform partial object serialization providing “paths” using Newtonsoft JSON.NET](https://stackoverflow.com/q/30304128/3744182). (In fact, this might be a duplicate. Agree?) There's an enhancement request for this, see [Feature request: ADD JsonProperty.ShouldSerialize(object target, string path) #1857](https://github.com/JamesNK/Newtonsoft.Json/issues/1857). – dbc Nov 07 '18 at 22:29

1 Answers1

2

I don't think there is anything helpful in the json.net library for this use case but you can do it manually:

JObject result = JObject.Parse(JsonConvert.SerializeObject(myObject));
foreach (var entry in remove)
{
    JObject current = result;
    var propertyChain = entry.Split(".").ToList();
    for(var i = 0; i < propertyChain.Count; i++)
    {
        if (i < propertyChain.Count - 1)
        {
            current = (JObject) current[propertyChain[i]];
        }
        else 
        {
            current.Remove(propertyChain[i]);
        }
    }
}
var myJson = result.ToString();
Daniel Rothig
  • 696
  • 3
  • 10