场景:
public abstract class JsonCreationConverter<T> : JsonConverter { /// <summary> /// this is very important, otherwise serialization breaks! /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// Create an instance of objectType, based properties in the JSON object /// </summary> /// <param name="objectType">type of object expected</param> /// <param name="jObject">contents of JSON object that will be /// deserialized</param> /// <returns></returns> protected abstract T Create(Type objectType, JObject jObject); public override bool CanConvert(Type objectType) { return typeof(T).IsAssignableFrom(objectType); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; // Load JObject from stream JObject jObject = JObject.Load(reader); // Create target object based on JObject T target = Create(objectType, jObject); // Populate the object properties serializer.Populate(jObject.CreateReader(), target); return target; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } }
[JsonConverter(typeof(UserConverter))] public class User { private class UserConverter : JsonCreationConverter<User> { protected override User Create(Type objectType, Newtonsoft.Json.Linq.JObject jObject) { if (jObject.Property("Course") !=null) { return new Student(); } else if (jObject.Property("WorkerType") != null) { return new Worker(); } else { return new User (); } } } public string Name { get; set; } public int Id { get; set; } } public class Student : User { public string Course { get; set; } } public class Worker : User { public string WorkerType { get; set; } }
[Route("api/Employee/AddUsers/")] public void AddUsers(List<User> users) { User s = users[0] as User; Student s1= users[1] as Student; Worker s2 = users[2] as Worker; s1 = users[2] as Student; if (s1 != null) { } //[{"Name":"1","Id":1},{"Course":"2","Name":"2","Id":2},{"WorkerType":"3","Name":"3","Id":3}] }