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 序列化
基础教程推荐
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
