Newtonsoft.json: JsonProperty.ItemConverterType 在基类上装饰时不起作用

创建于 2013-02-22  ·  3评论  ·  资料来源: JamesNK/Newtonsoft.Json

[TestFixture]
public class JsonPropertyItemConverterType
{
    public enum Thingy
    {
        Test
    }

    [JsonObject(MemberSerialization.OptIn)]
    public abstract class Base
    {
        [JsonProperty(PropertyName = "type", Required = Required.Always, Order = 0,
            ItemConverterType = typeof (StringEnumConverter))]
        public Thingy Type { get; internal set; }
    }

    public class Thing : Base
    {
        public Thing()
        {
            Type = Thingy.Test;
        }
    }

    [Test]
    public void ItShouldWork()
    {
        var json = JsonConvert.SerializeObject(new Thing());

        Assert.That(json, Is.EqualTo(@"{""type"":""Test""}"));
    }

    [Test]
    public void ItShouldWork2()
    {
        var json = JsonConvert.SerializeObject(new Thing(), new StringEnumConverter());

        Assert.That(json, Is.EqualTo(@"{""type"":""Test""}"));
    }
}

最有用的评论

我正在使用 wring 属性,

    [JsonConverter(typeof(StringEnumConverter))]

工作正常。

所有3条评论

propertyname 有效,但 itemcovertertype 无效

我正在使用 wring 属性,

    [JsonConverter(typeof(StringEnumConverter))]

工作正常。

6 年后,文档仍然误导我犯了这个错误。

此页面是否有帮助?
0 / 5 - 0 等级