using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace CustCreate
{
class Program
{
static string json = @"[
{
""Email"": ""blah@bubu.blah.boo"",
""JobType"": ""Email"",
""ScheduledTime"": ""2013-12-13T13:43:25.6881876Z"",
""Message"": ""Test 1""
},
{
""PhoneNo"": ""0912345678"",
""JobType"": ""SMS"",
""ScheduledTime"": ""2013-12-13T13:43:25.6891803Z"",
""Message"": ""Test 2""
}
]";
//自訂轉換器,繼承CustomCreationConverter<T>
class NotificationConverter : CustomCreationConverter<Notification>
{
//由於ReadJson會依JSON內容建立不同物件,用不到Create()
public override Notification Create(Type objectType)
{
throw new NotImplementedException();
}
//自訂解析JSON傳回物件的邏輯
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
//先取得JobType,由其決定建立物件
string jobType = jo["JobType"].ToString();
if (jobType == "Email")
{
//做法1: 由JObject取出建構式所需參數建構物件
var target = new EmailNotification(
jo["ScheduledTime"].Value<DateTime>(),
jo["Email"].ToString(),
jo["Message"].ToString()
);
return target;
}
else if (jobType == "SMS")
{
//做法2: 若物件支援無參數建構式,則可直接透過
// serializer.Populate()自動對應屬性
var target = new SMSNotification();
serializer.Populate(jo.CreateReader(), target);
return target;
}
else
throw new ApplicationException("Unsupported type: " + jobType);
}
}
static void Main(string[] args)
{
//JsonConvert.DeserializeObject時傳入自訂Converter
var list = JsonConvert.DeserializeObject<List<Notification>>(
json, new NotificationConverter());
var item = list[0];
Console.WriteLine("Type:{0} Email={1}",
item.JobType, (item as EmailNotification).Email);
item = list[1];
Console.WriteLine("Type:{0} PhoneNo={1}",
item.JobType, (item as SMSNotification).PhoneNo);
Console.Read();
}
}
}