【问题标题】:Serialize to JSON (using Json.Net) while ignoring inherited members序列化为 JSON(使用 Json.Net),同时忽略继承的成员
【发布时间】:2012-05-29 15:57:38
【问题描述】:

使用反射,我可以根据成员是继承的、声明的、公共的、私有的等来过滤成员。在使用 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));
}

【问题讨论】:

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


    【解决方案1】:

    我认为您可以使用自定义 ContractResolver 来实现您的目标。

    IContractResolver 接口提供了一种自定义 JsonSerializer 如何将 .NET 对象序列化和反序列化为 JSON 的方式。

    实现 IContractResolver 接口,然后分配一个 JsonSerializer 的实例可以让您控制对象是否是 序列化为 JSON 对象或 JSON 数组,对象成员应该 被序列化,它们是如何被序列化的以及它们被称为什么。

    无论如何,我在这里发现了同样的问题:Using JSON.net, how do I prevent serializing properties of a derived class, when used in a base class context?

    【讨论】:

      猜你喜欢
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 2020-01-31
      • 1970-01-01
      • 2016-08-27
      • 2012-11-28
      • 1970-01-01
      相关资源
      最近更新 更多