一个域中有三个类
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; }
}
来自ASP。. NET Web API I返回一个通用列表(曲目)。无论我尝试了什么,Web API都将Track的Artist属性返回为Artist而不是ArtistInfo。是否有某种方法可以在API的输出中限制这一点,只使用ArtistInfo?我不想编写额外的"ViewModels/dto"来处理这种情况。我可以用JSON序列化器的提示装饰ArtistInfo吗?
获得想要的结果的一种方法是使用可以限制序列化属性集的自定义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();
}
}
要使用转换器,将Track
类中的Artist
属性标记为[JsonConverter]
属性,如下所示。然后,只有Artist
的ArtistInfo
属性将被序列化。
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; }
}
演示
尽管Brian Rogers的回答是恰当的。但是如果你需要一个快速的解决方案,那么[JsonIgnore]属性将派上用场。
public class Artist : ArtistInfo
{
[JsonIgnore]
public DateTime Created { get; set; }
[JsonIgnore]
public int CreatedById { get; set; }
[JsonIgnore]
public DateTime Updated { get; set; }
[JsonIgnore]
public int UpdatedById { get; set; }
}
在这里查看Demo。我已经更新了Brian的代码