Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...