问题
I am trying to serialize an object with a static System.Version
field:
[JsonObject(MemberSerialization.OptIn)]
public class MyObj
{
[JsonProperty]
private static string testStr;
[JsonProperty(ItemConverterType = typeof(VersionConverter))]
private static Version ver = System.Reflection.Assembly...Version;
// some other non-serialized fields
// ...
}
I have learnt from this question that Version
needs a custom converter, which I added as ItemConverterType
. However, when I try to serialize it like this, it fails with the error: Expected Version object value:
var o = MyObj();
using (StreamWriter file = File.CreateText(filename))
{
JsonSerializer serializer = new JsonSerializer { Formatting = Formatting.Indented };
serializer.Serialize(file, o); // error
}
It works fine if I modify the attributes of the field like this:
public class MyObj
{
...
[JsonProperty]
[JsonConverter(typeof(VersionConverter))]
private static Version ver = System.Reflection.Assembly...Version;
...
I am new to attributes. Can you please shed some light as to why the first one fails ? I am quite sure I am not using Json.NET
correctly, but can't figure out why.
回答1:
ItemConverterType allows you to specify a converter to use for collection items. See Proper way of using Newtonsoft Json ItemConverterType. Since string
and Version
aren't treated as collections, it's ignored. For a converter on the property itself use [JsonConverter]
.
Conversely, if you had a static List<Version> versions
it would be appropriate to use [JsonProperty(ItemConverterType = typeof(VersionConverter))]
.
来源:https://stackoverflow.com/questions/38319305/why-serializing-version-with-jsonpropertyattribute-doesnt-work