本文介绍了我可以选择在运行时关闭 JsonIgnore 属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Newtonsoft.Json 从一组类中创建一个 JSON 文件.创建的文件非常大,因此我为属性创建了 JsonProperty 以减小大小,并为某些数据类型添加了 JsonIgnore 和自定义格式.

I am creating a JSON file with Newtonsoft.Json from a set of classes. The file created is very large, so I have created JsonProperty's for the properties to reduce the size and added JsonIgnore and custom formatting for some datatypes.

结果是从 24MB 减少到 1MB,这很棒;但是,我希望选择在运行时生成完整版本或缩减属性版本.

The result is a reduction from 24MB to 1MB, which is great; however, I'd like the option to produce either the full version or the reduced property version at runtime.

无论如何我可以让序列化程序选择性地使用属性吗?

Is there anyway I can get the serializer to optionally use the attributes?

推荐答案

是的,这可以使用自定义 ContractResolver 来完成.

Yes, this can be done using a custom ContractResolver.

你没有展示任何代码,所以我只是举个例子.假设我有一个类 Foo ,如下所示.我想要序列化输出中的 IdName 属性,但我绝对对 AlternateNameColor.我已经用 [JsonIgnore] 标记了它们.我希望出现描述,但有时这会变得很长,所以我使用了自定义 JsonConverter 来限制它的长度.我还想为描述使用较短的属性名称,所以我用 [JsonProperty("Desc")] 对其进行了标记.

You didn't show any code, so I'll just make up an example. Let's say I have a class Foo as shown below. I want the Id and Name properties in the serialization output, but I'm definitely not interested in the AlternateName and Color. I've marked those with [JsonIgnore]. I want the description to appear, but sometimes this can get really long, so I've used a custom JsonConverter to limit its length. I also want to use a shorter property name for the description, so I've marked it with [JsonProperty("Desc")].

class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
    [JsonIgnore]
    public string AlternateName { get; set; }
    [JsonProperty("Desc")]
    [JsonConverter(typeof(StringTruncatingConverter))]
    public string Description { get; set; }
    [JsonIgnore]
    public string Color { get; set; }
}

当我序列化上述实例时...

When I serialize an instance of the above...

Foo foo = new Foo
{
    Id = 1,
    Name = "Thing 1",
    AlternateName = "The First Thing",
    Description = "This is some lengthy text describing Thing 1 which you'll no doubt find very interesting and useful.",
    Color = "Yellow"
};

string json = JsonConvert.SerializeObject(foo, Formatting.Indented);

...我得到这个输出:

...I get this output:

{
  "Id": 1,
  "Name": "Thing 1",
  "Desc": "This is some lengthy text describing Thing 1 "
}

现在,假设我有时想获得完整的 JSON 输出,而忽略了我的自定义.我可以使用自定义 ContractResolver 以编程方式取消应用"类中的属性.这是解析器的代码:

Now, let's say that I sometimes want to get the full JSON output, ignoring my customizations. I can use a custom ContractResolver to programmatically "unapply" the attributes from the class. Here's the code for the resolver:

class IgnoreJsonAttributesResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
        foreach (var prop in props)
        {
            prop.Ignored = false;   // Ignore [JsonIgnore]
            prop.Converter = null;  // Ignore [JsonConverter]
            prop.PropertyName = prop.UnderlyingName;  // restore original property name
        }
        return props;
    }
}

要使用解析器,我将其添加到 JsonSerializerSettings 并将设置传递给序列化器,如下所示:

To use the resolver, I add it to the JsonSerializerSettings and pass the settings to the serializer like this:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new IgnoreJsonAttributesResolver();
settings.Formatting = Formatting.Indented;

string json = JsonConvert.SerializeObject(foo, settings);

输出现在包括被忽略的属性,并且描述不再被截断:

The output now includes the ignored properties, and the description is no longer truncated:

{
  "Id": 1,
  "Name": "Thing 1",
  "AlternateName": "The First Thing",
  "Description": "This is some lengthy text describing Thing 1 which you'll no doubt find very interesting and useful.",
  "Color": "Yellow"
}

完整演示:https://dotnetfiddle.net/WZpeWt

这篇关于我可以选择在运行时关闭 JsonIgnore 属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 15:27