Serialize JSON (using Json.Net), ignoring inherited members

Using reflection, I can filter the elements based on whether they are inherited, declared, public, closed, etc. Is there a way to do the same filtering when serializing an object using JSon.NET? p>

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)); } 
+4
source share
1 answer

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

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

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

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

+3
source

Source: https://habr.com/ru/post/1414932/


All Articles