在WebAPI中获取JSON.NET以序列化精确类型而不是子类

Bud*_*Joe 5 c# serialization json.net asp.net-web-api

我在一个域中有三个类

public class ArtistInfo
{
    private Guid Id { get; set; }
    public string Name { get; set; }
    public string DisplayName { get; set; }
    public bool IsGroup { get; set; }
    public bool IsActive { get; set; }
    public string Country { get; set; }
}

public class Artist : ArtistInfo
{
    public DateTime Created { get; set; }
    public int CreatedById { get; set; }
    public DateTime Updated { get; set; }
    public int UpdatedById { get; set; }
}

public class Track
{
    public string Title { get; set; }
    public string DisplayTitle { get; set; }
    public int Year { get; set; }
    public int Duration { get; set; }
    public int? TrackNumber { get; set; }
    //[SomeJsonAttribute]
    public ArtistInfo Artist { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

从ASP.NET Web API我返回一个通用List(Tracks).无论我尝试过什么,Web API都会将Track的Artist属性作为Artist而不是ArtistInfo返回.有没有办法在API的输出中限制这个只使用ArtistInfo?我不想写另外的"ViewModels/DTOs"来处理这种情况.我可以通过提示JSON Serializer来装饰ArtistInfo吗?

Bri*_*ers 1

获得所需结果的一种方法是使用JsonConverter可以限制序列化属性集的自定义。这是仅序列化基本类型的属性的一个T:

public class BaseTypeConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(T).IsAssignableFrom(objectType);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JObject obj = new JObject();
        foreach (PropertyInfo prop in typeof(T).GetProperties())
        {
            if (prop.CanRead)
            {
                obj.Add(prop.Name, JToken.FromObject(prop.GetValue(value)));
            }
        }
        obj.WriteTo(writer);
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用转换器,请使用属性标记类Artist中的属性,如下所示。然后,只有 的属性将被序列化。Track[JsonConverter]ArtistInfoArtist

public class Track
{
    public string Title { get; set; }
    public string DisplayTitle { get; set; }
    public int Year { get; set; }
    public int Duration { get; set; }
    public int? TrackNumber { get; set; }
    [JsonConverter(typeof(BaseTypeConverter<ArtistInfo>))]
    public ArtistInfo Artist { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

演示在这里