Why serializing Version with JsonPropertyAttribute doesn't work?

♀尐吖头ヾ 提交于 2019-11-27 08:36:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!