使用反射,我可以根据成员是继承的、声明的、公共(public)的还是私有(private)的等来过滤成员。在使用 JSon.NET 序列化对象时,有什么方法可以进行相同类型的过滤吗?
我的代码目前是:
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));
}
最佳答案
我认为您可以使用自定义 ContractResolver
来实现您的目标。
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.
无论如何,我在这里发现了同样的问题:Using JSON.net, how do I prevent serializing properties of a derived class, when used in a base class context?
关于c# - 序列化为 JSON(使用 Json.Net),同时忽略继承的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10802638/