Custom json serialization for each item in IEnumerable(IEnumerable 中每个项目的自定义 json 序列化)
问题描述
我正在使用 Json.NET 序列化具有枚举的 IEnumerable 和 DateTime 的对象.是这样的:
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?
推荐答案
事实证明,对于枚举,你必须使用 JsonPropertyAttribute 和 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 序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:IEnumerable 中每个项目的自定义 json 序列化
基础教程推荐
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 如果条件可以为空 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 从 C# 控制相机设备 2022-01-01
