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

查看:245
本文介绍了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?

推荐答案

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

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天全站免登陆