IEnumerable 中每个项目的自定义 json 序列化 [英] Custom json serialization for each item in IEnumerable

查看:34
本文介绍了IEnumerable 中每个项目的自定义 json 序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Json.NET 序列化具有枚举的 IEnumerableDateTime 的对象.是这样的:

I'm using Json.NET to serialize an object that has an IEnumerable of an enum and DateTime. It's something like:

class Chart
{
    // ...
    public IEnumerable<int> YAxis { get; set; }

    public IEnumerable<State> Data { get; set; }

    public IEnumerable<DateTime> XAxis { get; set; }
}

但我需要一个自定义 JsonConverter 来使枚举序列化为字符串并更改 DateTime 字符串格式.

But I need a custom JsonConverter to make the enum serialize as string and to change the DateTime string format.

我尝试使用 此处 中提到的 JsonConverter 属性用于枚举和自定义IsoDateTimeConverter 已完成此处:

I've tried using the JsonConverter attribute as mentioned here for enum and a custom IsoDateTimeConverter as done here:

[JsonConverter(typeof(StringEnumConverter))]
public IEnumerable<State> Data { get; set; }

[JsonConverter(typeof(MyDateTimeConverter))]
public IEnumerable<DateTime> XAxis { get; set; }

我希望它也适用于 IEnumerable,但不出所料:

I was hoping it would work for an IEnumerable too, but unsurprisingly it doesn't:

无法将WhereSelectArrayIterator`2[System.Int32,Model.State]"类型的对象转换为System.Enum"类型.

Unable to cast object of type 'WhereSelectArrayIterator`2[System.Int32,Model.State]' to type 'System.Enum'.

有没有办法说 JsonConverterAttribute 适用于每个项目而不是可枚举本身?

Is there any way to say that the JsonConverterAttribute applies to each item and not on the enumerable itself?

推荐答案

事实证明,对于枚举,你必须使用 JsonPropertyAttributeItemConverterType属性如下:

Turns out that for enumerables you have to use the JsonPropertyAttribute and the ItemConverterType property as follows:

[JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
public IEnumerable<State> Data { get; set; }

[JsonProperty(ItemConverterType = typeof(MyDateTimeConverter))]
public IEnumerable<DateTime> XAxis { get; set; }

文档中提到了这一点:

要将 JsonConverter 应用于集合中的项目,请使用 JsonArrayAttribute、JsonDictionaryAttribute 或 JsonPropertyAttribute 并将 ItemConverterType 属性设置为您要使用的转换器类型.

To apply a JsonConverter to the items in a collection, use either JsonArrayAttribute, JsonDictionaryAttribute or JsonPropertyAttribute and set the ItemConverterType property to the converter type you want to use.

您可能对 JsonArrayAttribute 感到困惑,但它无法定位属性.

You might be confused with JsonArrayAttribute, but it cannot target a property.

这篇关于IEnumerable 中每个项目的自定义 json 序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆