Ejemplo n.º 1
0
        public static object FromJson(
            JsonValue json,
            Type deserializationType,
            DeserializationContext context
            )
        {
            JsonObject jsonObject = json.AsJsonObject;

            var info = new SerializationInfo(
                deserializationType,
                new JsonDeserializationConverter(context)
                );

            foreach (var pair in jsonObject)
            {
                info.AddValue(pair.Key, (object)pair.Value);
            }

            ConstructorInfo constructor = deserializationType.GetConstructor(
                BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                null,
                new Type[] { typeof(SerializationInfo), typeof(StreamingContext) },
                null
                );

            if (constructor == null)
            {
                throw new UnisaveSerializationException(
                          $"The type {deserializationType} implements " +
                          $"{typeof(ISerializable)} but lacks the deserialization " +
                          $"constructor."
                          );
            }

            try
            {
                return(constructor.Invoke(
                           new object[] { info, context.GetStreamingContext() }
                           ));
            }
            catch (TargetInvocationException e)
            {
                if (e.InnerException != null)
                {
                    ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                }

                throw;
            }
        }