c# - 序列化为 JSON(使用 Json.Net),同时忽略继承的成员

标签 c# json serialization .net-4.0 json.net

使用反射,我可以根据成员是继承的、声明的、公共(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/

相关文章:

php - 如何修复由于单引号前删除斜杠而损坏的序列化字符串?

c# - 将已构建的 WinForms.Form 实例序列化为 VB 或 C# 源代码,就像 IDE 一样

c# - Windows 10 UWP 应用程序在启动画面后立即关闭/崩溃

json - 像javascript中的Stringify一样构造成json

java - JSON 将数据库解析为字符串

java - 如何轻松地将 Java 图形序列化为 JSON 或从 JSON 序列化?

c++ - 复制构造函数和基类 C++

c# - 查找具有用户指定大小的数组的平均值 C#

c# - 强制使用自定义属性

java - Spring REST Controller 返回带有空数据的 JSON