One way to get the desired result is to use a custom JsonConverter , which can limit the set of serialized properties. Here is the one that will serialize the properties of the base type 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(); } }
To use the converter, check the Artist property in your Track class with the [JsonConverter] attribute, as shown below. Then only the ArtistInfo Artist properties will be serialized.
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; } }
Demo here
source share