public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return(null);
            }
            // Load JObject from stream
            JObject jo = JObject.Load(reader);
            // Create target object based on JObject
            JToken value = null;

            jo.TryGetValue("$type", out value);
            var type = DerivedClassesRegister.GetTypeFromCode(value.Value <string>());

            if (type != null && !objectType.GetTypeInfo().IsAssignableFrom(type))
            {
                type = null;
            }
            var target = Activator.CreateInstance(type ?? objectType);

            // Populate the object properties
            using (JsonReader jObjectReader = CopyReaderForObject(reader, jo))
            {
                serializer.Populate(jObjectReader, target);
            }
            return(target);
        }
Esempio n. 2
0
        private Type getTransformation(ModelBindingContext bindingContext, out Type fitype, out Type fdtype, out string index)
        {
            fitype = null;  fdtype = null; index = null;
            var httpContext = bindingContext.HttpContext;
            var tr          = httpContext.RequestServices.GetService <RequestTransformationsRegister>();

            if (tr == null)
            {
                return(null);
            }
            index = tr.GetIndex(bindingContext.ModelName ?? string.Empty);
            if (index == null)
            {
                return(null);
            }
            if (index.Length > 0 && index[index.Length - 1] == '_')
            {
                return(DerivedClassesRegister.GetTypeFromCode(index));
            }
            else
            {
                return(TransformationsRegister.InverseTransform(bindingContext.ModelMetadata.ModelType, index, out fitype, out fdtype));
            }
        }