4

Using reflection, I'm able to filter members based on whether they are inherited, declared, public, private, etc. Is there any way to do the same sort of filtering when serializing an object using JSon.NET?

My code is currently:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public void addRequestParameters<T>(string key, T SerializableRequestParameters)
{
    //Serialize the object
    string json = JsonConvert.SerializeObject(SerializableRequestParameters, new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.All,
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
    });
    //Add it to an existing request (unrelated to this question)
    ((JObject)JSONRequest).Add(key, JToken.Parse(json));
}
Alain
  • 26,663
  • 20
  • 114
  • 184

1 Answers1

3

I think you could use a custom ContractResolver to achieve your goal.

The IContractResolver interface provides a way to customize how the JsonSerializer serializes and deserializes .NET objects to JSON.

Implementing the IContractResolver interface and then assigning an instance to a JsonSerializer lets you control whether the object is serialized as a JSON object or JSON array, what object members should be serialized, how they are serialized and what they are called.

Anyway, I found the same question here: Using JSON.net, how do I prevent serializing properties of a derived class, when used in a base class context?

Community
  • 1
  • 1
kntx
  • 154
  • 1
  • 5