Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

c# - Why serializing Version with JsonPropertyAttribute doesn't work?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...