8
There are two classes
public class Playlist {
public string Name { get; set; }
public Schedule Schedule1 { get; set; }
public Schedule Schedule2 { get; set; }
}
public interface Schedule {
string Name { get; set; }
}
[JsonObject(MemberSerialization = MemberSerialization.OptIn, IsReference = true)]
public class ScheduleImpl : Schedule {
[JsonProperty]
public string Name { get; set; }
}
each playlist has two schedules, the client code like below,
static void Main(string[] args) {
Playlist p1 = new Playlist { Name = "playlist1" };
p1.Schedule1 = new ScheduleImpl { Name = "schedule1" };
p1.Schedule2 = p1.Schedule1;
var content = Serialize(p1);
Console.WriteLine(content);
Console.WriteLine("----------------------------------------------------");
Console.ReadLine();
var p = Deserialize<Playlist>(content);
Console.WriteLine(p.Schedule1.Name);
Console.WriteLine(p.Schedule2.Name);
Console.WriteLine("press any key to exit.");
Console.ReadLine();
}
private static string Serialize(Playlist arg) {
var settings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };
return JsonConvert.SerializeObject(arg, Formatting.Indented, settings);
}
private static T Deserialize<T>(string arg) {
var settings = new JsonSerializerSettings();
settings.Converters = new JsonConverter[] {
new CustomCreationConverter<Schedule, ScheduleImpl>()
};
return JsonConvert.DeserializeObject<T>(arg, settings);
}
the custom creation converter can't handle the reference, should I parse the 'ref' by myself?
public class CustomCreationConverter<A, T> : CustomCreationConverter<A>
where T : A, new() {
public override A Create(Type objectType) {
return new T();
}
}
and the json output is,
{
"Name": "playlis