private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, string id)
        {
            contract.InvokeOnDeserializing(newObject);

            Dictionary <string, bool> requiredProperties =
                contract.Properties.Where(m => m.Required).ToDictionary(m => m.PropertyName, m => false);

            if (id != null)
            {
                _serializer.ReferenceResolver.AddReference(id, newObject);
            }

            do
            {
                switch (reader.TokenType)
                {
                case JsonToken.PropertyName:
                    string memberName = reader.Value.ToString();

                    if (!reader.Read())
                    {
                        throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
                    }

                    if (reader.TokenType != JsonToken.Null)
                    {
                        SetRequiredProperty(memberName, requiredProperties);
                    }

                    SetObjectMember(reader, newObject, contract, memberName);
                    break;

                case JsonToken.EndObject:
                    foreach (KeyValuePair <string, bool> requiredProperty in requiredProperties)
                    {
                        if (!requiredProperty.Value)
                        {
                            throw new JsonSerializationException("Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, requiredProperty.Key));
                        }
                    }

                    contract.InvokeOnDeserialized(newObject);
                    return(newObject);

                case JsonToken.Comment:
                    // ignore
                    break;

                default:
                    throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
                }
            } while (reader.Read());

            throw new JsonSerializationException("Unexpected end when deserializing object.");
        }
    private object CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, ConstructorInfo constructorInfo, string id)
    {
      ValidationUtils.ArgumentNotNull(constructorInfo, "constructorInfo");

      Type objectType = contract.UnderlyingType;

      IDictionary<JsonProperty, object> propertyValues = ResolvePropertyAndConstructorValues(contract, reader, objectType);

      IDictionary<ParameterInfo, object> constructorParameters = constructorInfo.GetParameters().ToDictionary(p => p, p => (object) null);
      IDictionary<JsonProperty, object> remainingPropertyValues = new Dictionary<JsonProperty, object>();

      foreach (KeyValuePair<JsonProperty, object> propertyValue in propertyValues)
      {
        ParameterInfo matchingConstructorParameter = constructorParameters.ForgivingCaseSensitiveFind(kv => kv.Key.Name, propertyValue.Key.UnderlyingName).Key;
        if (matchingConstructorParameter != null)
          constructorParameters[matchingConstructorParameter] = propertyValue.Value;
        else
          remainingPropertyValues.Add(propertyValue);
      }

      object createdObject = constructorInfo.Invoke(constructorParameters.Values.ToArray());

      if (id != null)
        Serializer.ReferenceResolver.AddReference(this, id, createdObject);

      contract.InvokeOnDeserializing(createdObject, Serializer.Context);

      // go through unused values and set the newly created object's properties
      foreach (KeyValuePair<JsonProperty, object> remainingPropertyValue in remainingPropertyValues)
      {
        JsonProperty property = remainingPropertyValue.Key;
        object value = remainingPropertyValue.Value;

        if (ShouldSetPropertyValue(remainingPropertyValue.Key, remainingPropertyValue.Value))
        {
          property.ValueProvider.SetValue(createdObject, value);
        }
        else if (!property.Writable && value != null)
        {
          // handle readonly collection/dictionary properties
          JsonContract propertyContract = Serializer.ContractResolver.ResolveContract(property.PropertyType);

          if (propertyContract.ContractType == JsonContractType.Array)
          {
            JsonArrayContract propertyArrayContract = propertyContract as JsonArrayContract;

            object createdObjectCollection = property.ValueProvider.GetValue(createdObject);
            if (createdObjectCollection != null)
            {
              IWrappedCollection createdObjectCollectionWrapper = propertyArrayContract.CreateWrapper(createdObjectCollection);
              IWrappedCollection newValues = propertyArrayContract.CreateWrapper(value);

              foreach (object newValue in newValues)
              {
                createdObjectCollectionWrapper.Add(newValue);
              }
            }
          }
          else if (propertyContract.ContractType == JsonContractType.Dictionary)
          {
            JsonDictionaryContract jsonDictionaryContract = propertyContract as JsonDictionaryContract;

            object createdObjectDictionary = property.ValueProvider.GetValue(createdObject);
            if (createdObjectDictionary != null)
            {
              IWrappedDictionary createdObjectDictionaryWrapper = jsonDictionaryContract.CreateWrapper(createdObjectDictionary);
              IWrappedDictionary newValues = jsonDictionaryContract.CreateWrapper(value);

              foreach (DictionaryEntry newValue in newValues)
              {
                createdObjectDictionaryWrapper.Add(newValue.Key, newValue.Value);
              }
            }
          }
        }
      }

      contract.InvokeOnDeserialized(createdObject, Serializer.Context);
      return createdObject;
    }
    private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, string id)
    {
      contract.InvokeOnDeserializing(newObject, Serializer.Context);

      Dictionary<JsonProperty, PropertyPresence> propertiesPresence =
        contract.Properties.ToDictionary(m => m, m => PropertyPresence.None);

      if (id != null)
        Serializer.ReferenceResolver.AddReference(this, id, newObject);

      int initialDepth = reader.Depth;

      do
      {
        switch (reader.TokenType)
        {
          case JsonToken.PropertyName:
            {
              string memberName = reader.Value.ToString();

              try
              {
                // attempt exact case match first
                // then try match ignoring case
                JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName);

                if (property == null)
                {
                  if (Serializer.MissingMemberHandling == MissingMemberHandling.Error)
                    throw CreateSerializationException(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType.Name));

                  reader.Skip();
                  continue;
                }

                if (property.PropertyContract == null)
                  property.PropertyContract = GetContractSafe(property.PropertyType);

                JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter);

                if (!ReadForType(reader, property.PropertyContract, propertyConverter != null, false))
                  throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));

                SetPropertyPresence(reader, property, propertiesPresence);

                SetPropertyValue(property, propertyConverter, reader, newObject);
              }
              catch (Exception ex)
              {
                if (IsErrorHandled(newObject, contract, memberName, reader.Path, ex))
                  HandleError(reader, initialDepth);
                else
                  throw;
              }
            }
            break;
          case JsonToken.EndObject:
            {
              foreach (KeyValuePair<JsonProperty, PropertyPresence> propertyPresence in propertiesPresence)
              {
                JsonProperty property = propertyPresence.Key;
                PropertyPresence presence = propertyPresence.Value;

                if (presence == PropertyPresence.None || presence == PropertyPresence.Null)
                {
                  try
                  {
                    switch (presence)
                    {
                      case PropertyPresence.None:
                        if (property.Required == Required.AllowNull || property.Required == Required.Always)
                          throw CreateSerializationException(reader, "Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName));

                        if (property.PropertyContract == null)
                          property.PropertyContract = GetContractSafe(property.PropertyType);

                        if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer.DefaultValueHandling), DefaultValueHandling.Populate)
                            && property.Writable)
                          property.ValueProvider.SetValue(newObject, EnsureType(reader, property.DefaultValue, CultureInfo.InvariantCulture, property.PropertyContract, property.PropertyType));
                        break;
                      case PropertyPresence.Null:
                        if (property.Required == Required.Always)
                          throw CreateSerializationException(reader, "Required property '{0}' expects a value but got null.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName));
                        break;
                    }
                  }
                  catch (Exception ex)
                  {
                    if (IsErrorHandled(newObject, contract, property.PropertyName, reader.Path, ex))
                      HandleError(reader, initialDepth);
                    else
                      throw;
                  }
                }
              }

              contract.InvokeOnDeserialized(newObject, Serializer.Context);
              return newObject;
            }
          case JsonToken.Comment:
            // ignore
            break;
          default:
            throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType);
        }
      } while (reader.Read());

      throw CreateSerializationException(reader, "Unexpected end when deserializing object.");
    }
Ejemplo n.º 4
0
        private object CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, string id)
        {
            Type objectType = contract.UnderlyingType;

            if (contract.ParametrizedConstructor == null)
            {
                throw new JsonSerializationException("Unable to find a constructor to use for type {0}. A class should either have a default constructor or only one constructor with arguments.".FormatWith(CultureInfo.InvariantCulture, objectType));
            }

            // create a dictionary to put retrieved values into
            IDictionary <JsonProperty, object> propertyValues = contract.Properties.Where(p => !p.Ignored).ToDictionary(kv => kv, kv => (object)null);

            bool exit = false;

            do
            {
                switch (reader.TokenType)
                {
                case JsonToken.PropertyName:
                    string memberName = reader.Value.ToString();
                    if (!reader.Read())
                    {
                        throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
                    }

                    // attempt exact case match first
                    // then try match ignoring case
                    JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName);

                    if (property != null)
                    {
                        if (!property.Ignored)
                        {
                            propertyValues[property] = CreateValueProperty(reader, property, null, true, null);
                        }
                        else
                        {
                            reader.Skip();
                        }
                    }
                    else
                    {
                        if (Serializer.MissingMemberHandling == MissingMemberHandling.Error)
                        {
                            throw new JsonSerializationException("Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name));
                        }

                        reader.Skip();
                    }
                    break;

                case JsonToken.EndObject:
                    exit = true;
                    break;

                default:
                    throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
                }
            } while (!exit && reader.Read());

            IDictionary <ParameterInfo, object> constructorParameters   = contract.ParametrizedConstructor.GetParameters().ToDictionary(p => p, p => (object)null);
            IDictionary <JsonProperty, object>  remainingPropertyValues = new Dictionary <JsonProperty, object>();

            foreach (KeyValuePair <JsonProperty, object> propertyValue in propertyValues)
            {
                ParameterInfo matchingConstructorParameter = constructorParameters.ForgivingCaseSensitiveFind(kv => kv.Key.Name, propertyValue.Key.PropertyName).Key;
                if (matchingConstructorParameter != null)
                {
                    constructorParameters[matchingConstructorParameter] = propertyValue.Value;
                }
                else
                {
                    remainingPropertyValues.Add(propertyValue);
                }
            }

            object createdObject = contract.ParametrizedConstructor.Invoke(constructorParameters.Values.ToArray());

            if (id != null)
            {
                Serializer.ReferenceResolver.AddReference(id, createdObject);
            }

            contract.InvokeOnDeserializing(createdObject, Serializer.Context);

            // go through unused values and set the newly created object's properties
            foreach (KeyValuePair <JsonProperty, object> remainingPropertyValue in remainingPropertyValues)
            {
                JsonProperty property = remainingPropertyValue.Key;
                object       value    = remainingPropertyValue.Value;

                if (ShouldSetPropertyValue(remainingPropertyValue.Key, remainingPropertyValue.Value))
                {
                    property.ValueProvider.SetValue(createdObject, value);
                }
            }

            contract.InvokeOnDeserialized(createdObject, Serializer.Context);
            return(createdObject);
        }
Ejemplo n.º 5
0
        private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, string id)
        {
            contract.InvokeOnDeserializing(newObject, Serializer.Context);

            Dictionary <JsonProperty, RequiredValue> requiredProperties =
                contract.Properties.Where(m => m.Required != Required.Default).ToDictionary(m => m, m => RequiredValue.None);

            if (id != null)
            {
                Serializer.ReferenceResolver.AddReference(id, newObject);
            }

            int initialDepth = reader.Depth;

            do
            {
                switch (reader.TokenType)
                {
                case JsonToken.PropertyName:
                    string memberName = reader.Value.ToString();

                    // attempt exact case match first
                    // then try match ignoring case
                    JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName);

                    if (property == null)
                    {
                        if (Serializer.MissingMemberHandling == MissingMemberHandling.Error)
                        {
                            throw new JsonSerializationException("Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType.Name));
                        }

                        reader.Skip();
                        continue;
                    }

                    if (!ReadForType(reader, property.PropertyType, property.Converter))
                    {
                        throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
                    }

                    SetRequiredProperty(reader, property, requiredProperties);

                    try
                    {
                        SetPropertyValue(property, reader, newObject);
                    }
                    catch (Exception ex)
                    {
                        if (IsErrorHandled(newObject, contract, memberName, ex))
                        {
                            HandleError(reader, initialDepth);
                        }
                        else
                        {
                            throw;
                        }
                    }
                    break;

                case JsonToken.EndObject:
                    foreach (KeyValuePair <JsonProperty, RequiredValue> requiredProperty in requiredProperties)
                    {
                        if (requiredProperty.Value == RequiredValue.None)
                        {
                            throw new JsonSerializationException("Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, requiredProperty.Key.PropertyName));
                        }
                        if (requiredProperty.Key.Required == Required.Always && requiredProperty.Value == RequiredValue.Null)
                        {
                            throw new JsonSerializationException("Required property '{0}' expects a value but got null.".FormatWith(CultureInfo.InvariantCulture, requiredProperty.Key.PropertyName));
                        }
                    }

                    contract.InvokeOnDeserialized(newObject, Serializer.Context);
                    return(newObject);

                case JsonToken.Comment:
                    // ignore
                    break;

                default:
                    throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
                }
            } while (reader.Read());

            throw new JsonSerializationException("Unexpected end when deserializing object.");
        }
    private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, string id)
    {
      contract.InvokeOnDeserializing(newObject, Serializer.Context);

      Dictionary<JsonProperty, RequiredValue> requiredProperties =
        contract.Properties.Where(m => m.Required != Required.Default).ToDictionary(m => m, m => RequiredValue.None);

      if (id != null)
        Serializer.ReferenceResolver.AddReference(id, newObject);

      int initialDepth = reader.Depth;

      do
      {
        switch (reader.TokenType)
        {
          case JsonToken.PropertyName:
            string memberName = reader.Value.ToString();

            // attempt exact case match first
            // then try match ignoring case
            JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName);

            if (property == null)
            {
              if (Serializer.MissingMemberHandling == MissingMemberHandling.Error)
                throw new JsonSerializationException("Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType.Name));

              reader.Skip();
              continue;
            }

            if (property.PropertyType == typeof(byte[]))
            {
              reader.ReadAsBytes();
            }
            else
            {
              if (!reader.Read())
                throw new JsonSerializationException(
                  "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
            }

            SetRequiredProperty(reader, property, requiredProperties);

            try
            {
              SetPropertyValue(property, reader, newObject);
            }
            catch (Exception ex)
            {
              if (IsErrorHandled(newObject, contract, memberName, ex))
                HandleError(reader, initialDepth);
              else
                throw;
            }
            break;
          case JsonToken.EndObject:
            foreach (KeyValuePair<JsonProperty, RequiredValue> requiredProperty in requiredProperties)
            {
              if (requiredProperty.Value == RequiredValue.None)
                throw new JsonSerializationException("Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, requiredProperty.Key.PropertyName));
              if (requiredProperty.Key.Required == Required.Always && requiredProperty.Value == RequiredValue.Null)
                throw new JsonSerializationException("Required property '{0}' expects a value but got null.".FormatWith(CultureInfo.InvariantCulture, requiredProperty.Key.PropertyName));
            }

            contract.InvokeOnDeserialized(newObject, Serializer.Context);
            return newObject;
          case JsonToken.Comment:
            // ignore
            break;
          default:
            throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
        }
      } while (reader.Read());

      throw new JsonSerializationException("Unexpected end when deserializing object.");
    }
    private object CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, string id)
    {
      Type objectType = contract.UnderlyingType;

      if (contract.ParametrizedConstructor == null)
        throw new JsonSerializationException("Unable to find a constructor to use for type {0}. A class should either have a default constructor or only one constructor with arguments.".FormatWith(CultureInfo.InvariantCulture, objectType));

      // create a dictionary to put retrieved values into
      IDictionary<JsonProperty, object> propertyValues = contract.Properties.Where(p => !p.Ignored).ToDictionary(kv => kv, kv => (object)null);

      bool exit = false;
      do
      {
        switch (reader.TokenType)
        {
          case JsonToken.PropertyName:
            string memberName = reader.Value.ToString();
            if (!reader.Read())
              throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));

            // attempt exact case match first
            // then try match ignoring case
            JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName);

            if (property != null)
            {
              if (!property.Ignored)
                propertyValues[property] = CreateValueProperty(reader, property, null, true, null);
              else
                reader.Skip();
            }
            else
            {
              if (Serializer.MissingMemberHandling == MissingMemberHandling.Error)
                throw new JsonSerializationException("Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name));

              reader.Skip();
            }
            break;
          case JsonToken.EndObject:
            exit = true;
            break;
          default:
            throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
        }
      } while (!exit && reader.Read());

      IDictionary<ParameterInfo, object> constructorParameters = contract.ParametrizedConstructor.GetParameters().ToDictionary(p => p, p => (object)null);
      IDictionary<JsonProperty, object> remainingPropertyValues = new Dictionary<JsonProperty, object>();

      foreach (KeyValuePair<JsonProperty, object> propertyValue in propertyValues)
      {
        ParameterInfo matchingConstructorParameter = constructorParameters.ForgivingCaseSensitiveFind(kv => kv.Key.Name, propertyValue.Key.PropertyName).Key;
        if (matchingConstructorParameter != null)
          constructorParameters[matchingConstructorParameter] = propertyValue.Value;
        else
          remainingPropertyValues.Add(propertyValue);
      }

      object createdObject = contract.ParametrizedConstructor.Invoke(constructorParameters.Values.ToArray());

      if (id != null)
        Serializer.ReferenceResolver.AddReference(id, createdObject);

      contract.InvokeOnDeserializing(createdObject, Serializer.Context);

      // go through unused values and set the newly created object's properties
      foreach (KeyValuePair<JsonProperty, object> remainingPropertyValue in remainingPropertyValues)
      {
        JsonProperty property = remainingPropertyValue.Key;
        object value = remainingPropertyValue.Value;

        if (ShouldSetPropertyValue(remainingPropertyValue.Key, remainingPropertyValue.Value))
          property.ValueProvider.SetValue(createdObject, value);
      }

      contract.InvokeOnDeserialized(createdObject, Serializer.Context);
      return createdObject;
    }
    private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, string id)
    {
      contract.InvokeOnDeserializing(newObject, Serializer.Context);

      // only need to keep a track of properies presence if they are required or a value should be defaulted if missing
      Dictionary<JsonProperty, PropertyPresence> propertiesPresence = (contract.HasRequiredOrDefaultValueProperties || HasFlag(Serializer.DefaultValueHandling, DefaultValueHandling.Populate))
        ? contract.Properties.ToDictionary(m => m, m => PropertyPresence.None)
        : null;

      if (id != null)
        Serializer.ReferenceResolver.AddReference(this, id, newObject);

      int initialDepth = reader.Depth;

      do
      {
        switch (reader.TokenType)
        {
          case JsonToken.PropertyName:
            {
              string memberName = reader.Value.ToString();

              try
              {
                // attempt exact case match first
                // then try match ignoring case
                JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName);

                if (property == null)
                {
                  if (Serializer.MissingMemberHandling == MissingMemberHandling.Error)
                    throw JsonSerializationException.Create(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType.Name));

                  reader.Skip();
                  continue;
                }

                if (property.PropertyContract == null)
                  property.PropertyContract = GetContractSafe(property.PropertyType);

                JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter, contract, member);

                if (!ReadForType(reader, property.PropertyContract, propertyConverter != null))
                  throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));

                SetPropertyPresence(reader, property, propertiesPresence);

                SetPropertyValue(property, propertyConverter, contract, member, reader, newObject);
              }
              catch (Exception ex)
              {
                if (IsErrorHandled(newObject, contract, memberName, reader.Path, ex))
                  HandleError(reader, true, initialDepth);
                else
                  throw;
              }
            }
            break;
          case JsonToken.EndObject:
            {
              EndObject(newObject, reader, contract, initialDepth, propertiesPresence);

              contract.InvokeOnDeserialized(newObject, Serializer.Context);
              return newObject;
            }
          case JsonToken.Comment:
            // ignore
            break;
          default:
            throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
        }
      } while (reader.Read());

      throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
    }
Ejemplo n.º 9
0
 private object CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ConstructorInfo constructorInfo, string id)
 {
   ValidationUtils.ArgumentNotNull((object) constructorInfo, "constructorInfo");
   Type underlyingType = contract.UnderlyingType;
   IDictionary<JsonProperty, object> dictionary1 = this.ResolvePropertyAndConstructorValues(contract, containerProperty, reader, underlyingType);
   IDictionary<ParameterInfo, object> dictionary2 = (IDictionary<ParameterInfo, object>) Enumerable.ToDictionary<ParameterInfo, ParameterInfo, object>((IEnumerable<ParameterInfo>) constructorInfo.GetParameters(), (Func<ParameterInfo, ParameterInfo>) (p => p), (Func<ParameterInfo, object>) (p => (object) null));
   IDictionary<JsonProperty, object> dictionary3 = (IDictionary<JsonProperty, object>) new Dictionary<JsonProperty, object>();
   foreach (KeyValuePair<JsonProperty, object> keyValuePair in (IEnumerable<KeyValuePair<JsonProperty, object>>) dictionary1)
   {
     ParameterInfo key = StringUtils.ForgivingCaseSensitiveFind<KeyValuePair<ParameterInfo, object>>((IEnumerable<KeyValuePair<ParameterInfo, object>>) dictionary2, (Func<KeyValuePair<ParameterInfo, object>, string>) (kv => kv.Key.Name), keyValuePair.Key.UnderlyingName).Key;
     if (key != null)
       dictionary2[key] = keyValuePair.Value;
     else
       dictionary3.Add(keyValuePair);
   }
   object obj1 = constructorInfo.Invoke(Enumerable.ToArray<object>((IEnumerable<object>) dictionary2.Values));
   if (id != null)
     this.AddReference(reader, id, obj1);
   contract.InvokeOnDeserializing(obj1, this.Serializer.Context);
   foreach (KeyValuePair<JsonProperty, object> keyValuePair in (IEnumerable<KeyValuePair<JsonProperty, object>>) dictionary3)
   {
     JsonProperty key = keyValuePair.Key;
     object obj2 = keyValuePair.Value;
     if (this.ShouldSetPropertyValue(keyValuePair.Key, keyValuePair.Value))
       key.ValueProvider.SetValue(obj1, obj2);
     else if (!key.Writable && obj2 != null)
     {
       JsonContract jsonContract = this.Serializer.ContractResolver.ResolveContract(key.PropertyType);
       if (jsonContract.ContractType == JsonContractType.Array)
       {
         JsonArrayContract jsonArrayContract = (JsonArrayContract) jsonContract;
         object list = key.ValueProvider.GetValue(obj1);
         if (list != null)
         {
           IWrappedCollection wrapper = jsonArrayContract.CreateWrapper(list);
           foreach (object obj3 in (IEnumerable) jsonArrayContract.CreateWrapper(obj2))
             wrapper.Add(obj3);
         }
       }
       else if (jsonContract.ContractType == JsonContractType.Dictionary)
       {
         JsonDictionaryContract dictionaryContract = (JsonDictionaryContract) jsonContract;
         object dictionary4 = key.ValueProvider.GetValue(obj1);
         if (dictionary4 != null)
         {
           IWrappedDictionary wrapper = dictionaryContract.CreateWrapper(dictionary4);
           foreach (DictionaryEntry dictionaryEntry in (IDictionary) dictionaryContract.CreateWrapper(obj2))
             wrapper.Add(dictionaryEntry.Key, dictionaryEntry.Value);
         }
       }
     }
   }
   contract.InvokeOnDeserialized(obj1, this.Serializer.Context);
   return obj1;
 }
Ejemplo n.º 10
0
 private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, string id)
 {
   contract.InvokeOnDeserializing(newObject, this.Serializer.Context);
   Dictionary<JsonProperty, JsonSerializerInternalReader.PropertyPresence> dictionary = contract.HasRequiredOrDefaultValueProperties || this.HasFlag(this.Serializer.DefaultValueHandling, DefaultValueHandling.Populate) ? Enumerable.ToDictionary<JsonProperty, JsonProperty, JsonSerializerInternalReader.PropertyPresence>((IEnumerable<JsonProperty>) contract.Properties, (Func<JsonProperty, JsonProperty>) (m => m), (Func<JsonProperty, JsonSerializerInternalReader.PropertyPresence>) (m => JsonSerializerInternalReader.PropertyPresence.None)) : (Dictionary<JsonProperty, JsonSerializerInternalReader.PropertyPresence>) null;
   if (id != null)
     this.AddReference(reader, id, newObject);
   int depth = reader.Depth;
   bool flag = false;
   do
   {
     switch (reader.TokenType)
     {
       case JsonToken.PropertyName:
         string propertyName = reader.Value.ToString();
         try
         {
           JsonProperty closestMatchProperty = contract.Properties.GetClosestMatchProperty(propertyName);
           if (closestMatchProperty == null)
           {
             if (this.Serializer.MissingMemberHandling == MissingMemberHandling.Error)
               throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Could not find member '{0}' on object of type '{1}'", (IFormatProvider) CultureInfo.InvariantCulture, (object) propertyName, (object) contract.UnderlyingType.Name));
             reader.Skip();
             goto case JsonToken.Comment;
           }
           else
           {
             if (closestMatchProperty.PropertyContract == null)
               closestMatchProperty.PropertyContract = this.GetContractSafe(closestMatchProperty.PropertyType);
             JsonConverter converter = this.GetConverter(closestMatchProperty.PropertyContract, closestMatchProperty.MemberConverter, (JsonContainerContract) contract, member);
             if (!this.ReadForType(reader, closestMatchProperty.PropertyContract, converter != null))
               throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unexpected end when setting {0}'s value.", (IFormatProvider) CultureInfo.InvariantCulture, (object) propertyName));
             this.SetPropertyPresence(reader, closestMatchProperty, dictionary);
             this.SetPropertyValue(closestMatchProperty, converter, (JsonContainerContract) contract, member, reader, newObject);
             goto case JsonToken.Comment;
           }
         }
         catch (Exception ex)
         {
           if (this.IsErrorHandled(newObject, (JsonContract) contract, (object) propertyName, reader.Path, ex))
           {
             this.HandleError(reader, true, depth);
             goto case JsonToken.Comment;
           }
           else
             throw;
         }
       case JsonToken.Comment:
         continue;
       case JsonToken.EndObject:
         flag = true;
         goto case JsonToken.Comment;
       default:
         throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + (object) reader.TokenType);
     }
   }
   while (!flag && reader.Read());
   if (!flag)
     this.ThrowUnexpectedEndException(reader, (JsonContract) contract, newObject, "Unexpected end when deserializing object.");
   this.EndObject(newObject, reader, contract, depth, dictionary);
   contract.InvokeOnDeserialized(newObject, this.Serializer.Context);
   return newObject;
 }
        private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, string id)
        {
            contract.InvokeOnDeserializing(newObject);

              Dictionary<string, bool> requiredProperties =
            contract.Properties.Where(m => m.Required).ToDictionary(m => m.PropertyName, m => false);

              if (id != null)
            _serializer.ReferenceResolver.AddReference(id, newObject);

              do
              {
            switch (reader.TokenType)
            {
              case JsonToken.PropertyName:
            string memberName = reader.Value.ToString();

            if (!reader.Read())
              throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));

            if (reader.TokenType != JsonToken.Null)
              SetRequiredProperty(memberName, requiredProperties);

            SetObjectMember(reader, newObject, contract, memberName);
            break;
              case JsonToken.EndObject:
            foreach (KeyValuePair<string, bool> requiredProperty in requiredProperties)
            {
              if (!requiredProperty.Value)
                throw new JsonSerializationException("Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, requiredProperty.Key));
            }

            contract.InvokeOnDeserialized(newObject);
            return newObject;
              case JsonToken.Comment:
            // ignore
            break;
              default:
            throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
            }
              } while (reader.Read());

              throw new JsonSerializationException("Unexpected end when deserializing object.");
        }
        private object CreateObjectFromNonDefaultConstructor(JsonObjectContract contract, JsonReader reader)
        {
            Type objectType = contract.UnderlyingType;

              // object should have a single constructor
              ConstructorInfo c = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance).SingleOrDefault();

              if (c == null)
            throw new JsonSerializationException("Could not find a public constructor for type {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));

              // create a dictionary to put retrieved values into
              IDictionary<JsonProperty, object> propertyValues = contract.Properties.Where(p => !p.Ignored).ToDictionary(kv => kv, kv => (object)null);

              bool exit = false;
              do
              {
            switch (reader.TokenType)
            {
              case JsonToken.PropertyName:
            string memberName = reader.Value.ToString();
            if (!reader.Read())
              throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));

            JsonProperty property;
            // attempt exact case match first
            // then try match ignoring case
            if (contract.Properties.TryGetClosestMatchProperty(memberName, out property))
            {
              if (!property.Ignored)
              {
                Type memberType = ReflectionUtils.GetMemberUnderlyingType(property.Member);
                propertyValues[property] = CreateValue(reader, memberType, null, property.MemberConverter);
              }
            }
            else
            {
              if (_serializer.MissingMemberHandling == MissingMemberHandling.Error)
                throw new JsonSerializationException("Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name));

              reader.Skip();
            }
            break;
              case JsonToken.EndObject:
            exit = true;
            break;
              default:
            throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
            }
              } while (!exit && reader.Read());

              IDictionary<ParameterInfo, object> constructorParameters = c.GetParameters().ToDictionary(p => p, p => (object)null);
              IDictionary<JsonProperty, object> remainingPropertyValues = new Dictionary<JsonProperty, object>();

              foreach (KeyValuePair<JsonProperty, object> propertyValue in propertyValues)
              {
            ParameterInfo matchingConstructorParameter = constructorParameters.ForgivingCaseSensitiveFind(kv => kv.Key.Name, propertyValue.Key.PropertyName).Key;
            if (matchingConstructorParameter != null)
              constructorParameters[matchingConstructorParameter] = propertyValue.Value;
            else
              remainingPropertyValues.Add(propertyValue);
              }

              object createdObject = ReflectionUtils.CreateInstance(objectType, constructorParameters.Values.ToArray());
              contract.InvokeOnDeserializing(createdObject);

              // go through unused values and set the newly created object's properties
              foreach (KeyValuePair<JsonProperty, object> remainingPropertyValue in remainingPropertyValues)
              {
            if (ShouldSetPropertyValue(remainingPropertyValue.Key, remainingPropertyValue.Value))
              ReflectionUtils.SetMemberValue(remainingPropertyValue.Key.Member, createdObject, remainingPropertyValue.Value);
              }

              contract.InvokeOnDeserialized(createdObject);
              return createdObject;
        }
Ejemplo n.º 13
0
        private object CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, ConstructorInfo constructorInfo, string id)
        {
            ValidationUtils.ArgumentNotNull(constructorInfo, "constructorInfo");
            Type underlyingType = contract.UnderlyingType;
            IDictionary <JsonProperty, object>  dictionary  = ResolvePropertyAndConstructorValues(contract, reader, underlyingType);
            IDictionary <ParameterInfo, object> dictionary2 = ((IEnumerable <ParameterInfo>)constructorInfo.GetParameters()).ToDictionary((Func <ParameterInfo, ParameterInfo>)((ParameterInfo p) => p), (Func <ParameterInfo, object>)((ParameterInfo p) => null));
            IDictionary <JsonProperty, object>  dictionary3 = new Dictionary <JsonProperty, object>();

            foreach (KeyValuePair <JsonProperty, object> item in dictionary)
            {
                ParameterInfo key = dictionary2.ForgivingCaseSensitiveFind((KeyValuePair <ParameterInfo, object> kv) => kv.Key.Name, item.Key.UnderlyingName).Key;
                if (key != null)
                {
                    dictionary2[key] = item.Value;
                }
                else
                {
                    dictionary3.Add(item);
                }
            }
            object obj = constructorInfo.Invoke(dictionary2.Values.ToArray());

            if (id != null)
            {
                base.Serializer.ReferenceResolver.AddReference(this, id, obj);
            }
            contract.InvokeOnDeserializing(obj, base.Serializer.Context);
            foreach (KeyValuePair <JsonProperty, object> item2 in dictionary3)
            {
                JsonProperty key2  = item2.Key;
                object       value = item2.Value;
                if (ShouldSetPropertyValue(item2.Key, item2.Value))
                {
                    key2.ValueProvider.SetValue(obj, value);
                }
                else
                {
                    if (key2.Writable || value == null)
                    {
                        continue;
                    }
                    JsonContract jsonContract = base.Serializer.ContractResolver.ResolveContract(key2.PropertyType);
                    if (jsonContract is JsonArrayContract)
                    {
                        JsonArrayContract jsonArrayContract = jsonContract as JsonArrayContract;
                        object            value2            = key2.ValueProvider.GetValue(obj);
                        if (value2 == null)
                        {
                            continue;
                        }
                        IWrappedCollection wrappedCollection  = jsonArrayContract.CreateWrapper(value2);
                        IWrappedCollection wrappedCollection2 = jsonArrayContract.CreateWrapper(value);
                        foreach (object item3 in wrappedCollection2)
                        {
                            wrappedCollection.Add(item3);
                        }
                    }
                    else
                    {
                        if (!(jsonContract is JsonDictionaryContract))
                        {
                            continue;
                        }
                        JsonDictionaryContract jsonDictionaryContract = jsonContract as JsonDictionaryContract;
                        object value3 = key2.ValueProvider.GetValue(obj);
                        if (value3 == null)
                        {
                            continue;
                        }
                        IWrappedDictionary wrappedDictionary  = jsonDictionaryContract.CreateWrapper(value3);
                        IWrappedDictionary wrappedDictionary2 = jsonDictionaryContract.CreateWrapper(value);
                        foreach (DictionaryEntry item4 in wrappedDictionary2)
                        {
                            wrappedDictionary.Add(item4.Key, item4.Value);
                        }
                    }
                }
            }
            contract.InvokeOnDeserialized(obj, base.Serializer.Context);
            return(obj);
        }
Ejemplo n.º 14
0
        private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, string id)
        {
            contract.InvokeOnDeserializing(newObject, base.Serializer.Context);
            Dictionary <JsonProperty, PropertyPresence> dictionary = contract.Properties.ToDictionary((JsonProperty m) => m, (JsonProperty m) => PropertyPresence.None);

            if (id != null)
            {
                base.Serializer.ReferenceResolver.AddReference(this, id, newObject);
            }
            int depth = reader.Depth;

            do
            {
                switch (reader.TokenType)
                {
                case JsonToken.PropertyName:
                    {
                        string text = reader.Value.ToString();
                        try
                        {
                            JsonProperty key = contract.Properties.GetClosestMatchProperty(text);
                            if (key == null)
                            {
                                if (base.Serializer.MissingMemberHandling == MissingMemberHandling.Error)
                                {
                                    throw new JsonSerializationException("Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, text, contract.UnderlyingType.Name));
                                }
                                reader.Skip();
                            }
                            else
                            {
                                if (!ReadForType(reader, key.PropertyType, key.Converter))
                                {
                                    throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, text));
                                }
                                SetPropertyPresence(reader, key, dictionary);
                                SetPropertyValue(key, reader, newObject);
                            }
                        }
                        catch (Exception ex)
                        {
                            if (IsErrorHandled(newObject, contract, text, ex))
                            {
                                HandleError(reader, depth);
                                break;
                            }
                            throw;
                        }
                        break;
                    }

                case JsonToken.EndObject:
                    foreach (KeyValuePair <JsonProperty, PropertyPresence> item in dictionary)
                    {
                        JsonProperty key = item.Key;
                        switch (item.Value)
                        {
                        case PropertyPresence.None:
                            if (key.Required == Required.AllowNull || key.Required == Required.Always)
                            {
                                throw new JsonSerializationException("Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, key.PropertyName));
                            }
                            if (HasFlag(key.DefaultValueHandling.GetValueOrDefault(base.Serializer.DefaultValueHandling), DefaultValueHandling.Populate) && key.Writable)
                            {
                                key.ValueProvider.SetValue(newObject, EnsureType(key.DefaultValue, CultureInfo.InvariantCulture, key.PropertyType));
                            }
                            break;

                        case PropertyPresence.Null:
                            if (key.Required == Required.Always)
                            {
                                throw new JsonSerializationException("Required property '{0}' expects a value but got null.".FormatWith(CultureInfo.InvariantCulture, key.PropertyName));
                            }
                            break;
                        }
                    }
                    contract.InvokeOnDeserialized(newObject, base.Serializer.Context);
                    return(newObject);

                default:
                    throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);

                case JsonToken.Comment:
                    break;
                }
            }while (reader.Read());
            throw new JsonSerializationException("Unexpected end when deserializing object.");
        }
        private object CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, ConstructorInfo constructorInfo, string id)
        {
            ValidationUtils.ArgumentNotNull(constructorInfo, "constructorInfo");
            Type underlyingType = contract.UnderlyingType;
            IDictionary <JsonProperty, object>  dictionary  = ResolvePropertyAndConstructorValues(contract, reader, underlyingType);
            IDictionary <ParameterInfo, object> dictionary2 = ((IEnumerable <ParameterInfo>)constructorInfo.GetParameters()).ToDictionary((Func <ParameterInfo, ParameterInfo>)((ParameterInfo p) => p), (Func <ParameterInfo, object>)((ParameterInfo p) => null));
            IDictionary <JsonProperty, object>  dictionary3 = new Dictionary <JsonProperty, object>();

            foreach (KeyValuePair <JsonProperty, object> item in dictionary)
            {
                ParameterInfo key = dictionary2.ForgivingCaseSensitiveFind((KeyValuePair <ParameterInfo, object> kv) => kv.Key.Name, item.Key.UnderlyingName).Key;
                if (key != null)
                {
                    dictionary2[key] = item.Value;
                }
                else
                {
                    dictionary3.Add(item);
                }
            }
            object obj = constructorInfo.Invoke(dictionary2.Values.ToArray());

            if (id != null)
            {
                base.Serializer.ReferenceResolver.AddReference(this, id, obj);
            }
            contract.InvokeOnDeserializing(obj, base.Serializer.Context);
            foreach (KeyValuePair <JsonProperty, object> item2 in dictionary3)
            {
                JsonProperty key2  = item2.Key;
                object       value = item2.Value;
                if (ShouldSetPropertyValue(item2.Key, item2.Value))
                {
                    key2.ValueProvider.SetValue(obj, value);
                }
                else if (!key2.Writable && value != null)
                {
                    JsonContract jsonContract = base.Serializer.ContractResolver.ResolveContract(key2.PropertyType);
                    if (jsonContract is JsonArrayContract)
                    {
                        JsonArrayContract jsonArrayContract = jsonContract as JsonArrayContract;
                        object            value2            = key2.ValueProvider.GetValue(obj);
                        if (value2 != null)
                        {
                            IWrappedCollection wrappedCollection  = jsonArrayContract.CreateWrapper(value2);
                            IWrappedCollection wrappedCollection2 = jsonArrayContract.CreateWrapper(value);
                            IEnumerator        enumerator3        = wrappedCollection2.GetEnumerator();
                            try
                            {
                                while (enumerator3.MoveNext())
                                {
                                    object current3 = enumerator3.Current;
                                    wrappedCollection.Add(current3);
                                }
                            }
                            finally
                            {
                                IDisposable disposable;
                                if ((disposable = (enumerator3 as IDisposable)) != null)
                                {
                                    disposable.Dispose();
                                }
                            }
                        }
                    }
                    else if (jsonContract is JsonDictionaryContract)
                    {
                        JsonDictionaryContract jsonDictionaryContract = jsonContract as JsonDictionaryContract;
                        object value3 = key2.ValueProvider.GetValue(obj);
                        if (value3 != null)
                        {
                            IWrappedDictionary    wrappedDictionary  = jsonDictionaryContract.CreateWrapper(value3);
                            IWrappedDictionary    wrappedDictionary2 = jsonDictionaryContract.CreateWrapper(value);
                            IDictionaryEnumerator enumerator4        = wrappedDictionary2.GetEnumerator();
                            try
                            {
                                while (enumerator4.MoveNext())
                                {
                                    DictionaryEntry dictionaryEntry = (DictionaryEntry)enumerator4.Current;
                                    wrappedDictionary.Add(dictionaryEntry.Key, dictionaryEntry.Value);
                                }
                            }
                            finally
                            {
                                IDisposable disposable2;
                                if ((disposable2 = (enumerator4 as IDisposable)) != null)
                                {
                                    disposable2.Dispose();
                                }
                            }
                        }
                    }
                }
            }
            contract.InvokeOnDeserialized(obj, base.Serializer.Context);
            return(obj);
        }
        private object CreateObjectFromNonDefaultConstructor(JsonObjectContract contract, JsonReader reader)
        {
            Type objectType = contract.UnderlyingType;

            // object should have a single constructor
            ConstructorInfo c = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance).SingleOrDefault();

            if (c == null)
            {
                throw new JsonSerializationException("Could not find a public constructor for type {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
            }

            // create a dictionary to put retrieved values into
            IDictionary <JsonProperty, object> propertyValues = contract.Properties.Where(p => !p.Ignored).ToDictionary(kv => kv, kv => (object)null);

            bool exit = false;

            do
            {
                switch (reader.TokenType)
                {
                case JsonToken.PropertyName:
                    string memberName = reader.Value.ToString();
                    if (!reader.Read())
                    {
                        throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
                    }

                    JsonProperty property;
                    // attempt exact case match first
                    // then try match ignoring case
                    if (contract.Properties.TryGetClosestMatchProperty(memberName, out property))
                    {
                        if (!property.Ignored)
                        {
                            Type memberType = ReflectionUtils.GetMemberUnderlyingType(property.Member);
                            propertyValues[property] = CreateValue(reader, memberType, null, property.MemberConverter);
                        }
                    }
                    else
                    {
                        if (_serializer.MissingMemberHandling == MissingMemberHandling.Error)
                        {
                            throw new JsonSerializationException("Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name));
                        }

                        reader.Skip();
                    }
                    break;

                case JsonToken.EndObject:
                    exit = true;
                    break;

                default:
                    throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType);
                }
            } while (!exit && reader.Read());

            IDictionary <ParameterInfo, object> constructorParameters   = c.GetParameters().ToDictionary(p => p, p => (object)null);
            IDictionary <JsonProperty, object>  remainingPropertyValues = new Dictionary <JsonProperty, object>();

            foreach (KeyValuePair <JsonProperty, object> propertyValue in propertyValues)
            {
                ParameterInfo matchingConstructorParameter = constructorParameters.ForgivingCaseSensitiveFind(kv => kv.Key.Name, propertyValue.Key.PropertyName).Key;
                if (matchingConstructorParameter != null)
                {
                    constructorParameters[matchingConstructorParameter] = propertyValue.Value;
                }
                else
                {
                    remainingPropertyValues.Add(propertyValue);
                }
            }

            object createdObject = ReflectionUtils.CreateInstance(objectType, constructorParameters.Values.ToArray());

            contract.InvokeOnDeserializing(createdObject);

            // go through unused values and set the newly created object's properties
            foreach (KeyValuePair <JsonProperty, object> remainingPropertyValue in remainingPropertyValues)
            {
                if (ShouldSetPropertyValue(remainingPropertyValue.Key, remainingPropertyValue.Value))
                {
                    ReflectionUtils.SetMemberValue(remainingPropertyValue.Key.Member, createdObject, remainingPropertyValue.Value);
                }
            }

            contract.InvokeOnDeserialized(createdObject);
            return(createdObject);
        }