using Microsoft.VisualBasic.CompilerServices; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace MEU.API { [JsonConverter(typeof(PagedDataConverter))] public class FromBodyGenericType<T, U> where T : class where U : class { public T BODY_PART_T { get; set; } public U BODY_PART_U { get; set; } } public class PagedDataConverter : JsonConverter { public override bool CanConvert(Type objectType) { return true; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var instance = Activator.CreateInstance(objectType); //MyCustomType myCustomType = new MyCustomType();//for null values Dictionary<string, KeyValuePair< string, Type>> dcValue = new Dictionary<string, KeyValuePair<string, Type>>(); foreach (var prop in objectType.GetProperties()) { string fullName = prop.PropertyType.FullName.Split(',')[0]; string name = ""; //"MEU.API.Models.working_shift" if (fullName.Contains("System.Collections.Generic.List")) { string[] names = fullName.Split('.'); name = "list_" + names.LastOrDefault().Replace("\"", ""); } else { string[] names = fullName.Split('.'); name = names.LastOrDefault().Replace("\"", ""); } dcValue.Add(name, new KeyValuePair<string,Type>( prop.Name.ToUpper(),prop.PropertyType)); //var result = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(addrayData[name]), prop.PropertyType); } if (reader.TokenType != JsonToken.Null) { Dictionary<string, JToken> addrayData = new Dictionary<string, JToken>(); JToken token1 = JToken.Load(reader); Dictionary<string, JToken> addkey = new Dictionary<string, JToken>(); Dictionary<string, JToken> removedkey = new Dictionary<string, JToken>(); Dictionary<string, string> dict = new Dictionary<string, string>(); foreach (var pair in token1 as JObject) { if (pair.Key.StartsWith("BODY_PART")) { continue; } dict.Add(pair.Key, dcValue[pair.Key].Key); var data = JsonConvert.DeserializeObject(pair.Value.ToString(), dcValue[pair.Key].Value); PropertyInfo prop = instance.GetType().GetProperty(dcValue[pair.Key].Key); prop.SetValue(instance, data, null); } return instance; } return null;// myCustomType; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new Exception("Have not implment"); } } }