我正在使用 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 序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
读取 XML 时忽略空格Ignore whitespace while reading XML(读取 XML 时忽略空格)
带有检查空元素的 XML 到 LINQXML to LINQ with Checking Null Elements(带有检查空元素的 XML 到 LINQ)
在 C# 中读取带有未闭合标签的 XMLReading XML with unclosed tags in C#(在 C# 中读取带有未闭合标签的 XML)
在 C# 中使用 Html 敏捷性解析表格、单元格Parsing tables, cells with Html agility in C#(在 C# 中使用 Html 敏捷性解析表格、单元格)
使用 LINQ 从 xml 中删除元素delete element from xml using LINQ(使用 LINQ 从 xml 中删除元素)
解析格式错误的 XMLParse malformed XML(解析格式错误的 XML)