当前位置: 首页>>代码示例>>C#>>正文


C# JsonObjectContract.InvokeOnDeserializing方法代码示例

本文整理汇总了C#中Newtonsoft.Json.Serialization.JsonObjectContract.InvokeOnDeserializing方法的典型用法代码示例。如果您正苦于以下问题:C# JsonObjectContract.InvokeOnDeserializing方法的具体用法?C# JsonObjectContract.InvokeOnDeserializing怎么用?C# JsonObjectContract.InvokeOnDeserializing使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Newtonsoft.Json.Serialization.JsonObjectContract的用法示例。


在下文中一共展示了JsonObjectContract.InvokeOnDeserializing方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: PopulateObject

    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:
//.........这里部分代码省略.........
开发者ID:bladefist,项目名称:Newtonsoft.Json,代码行数:101,代码来源:JsonSerializerInternalReader.cs

示例2: CreateObjectFromNonDefaultConstructor

    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;
    }
开发者ID:bladefist,项目名称:Newtonsoft.Json,代码行数:80,代码来源:JsonSerializerInternalReader.cs

示例3: CreateObjectFromNonDefaultConstructor

    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;
    }
开发者ID:nathanpalmer,项目名称:ravendb,代码行数:79,代码来源:JsonSerializerInternalReader.cs

示例4: PopulateObject

    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.");
    }
开发者ID:nathanpalmer,项目名称:ravendb,代码行数:78,代码来源:JsonSerializerInternalReader.cs

示例5: PopulateObject

    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.");
    }
开发者ID:Contatta,项目名称:Newtonsoft.Json,代码行数:75,代码来源:JsonSerializerInternalReader.cs

示例6: CreateObjectFromNonDefaultConstructor

 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;
 }
开发者ID:Zeludon,项目名称:FEZ,代码行数:55,代码来源:JsonSerializerInternalReader.cs

示例7: PopulateObject

 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;
 }
开发者ID:Zeludon,项目名称:FEZ,代码行数:62,代码来源:JsonSerializerInternalReader.cs

示例8: PopulateObject

        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.");
        }
开发者ID:BGCX262,项目名称:zulu-omoto-pos-client-svn-to-git,代码行数:44,代码来源:JsonSerializerReader.cs

示例9: CreateObjectFromNonDefaultConstructor

        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;
        }
开发者ID:BGCX262,项目名称:zulu-omoto-pos-client-svn-to-git,代码行数:75,代码来源:JsonSerializerReader.cs


注:本文中的Newtonsoft.Json.Serialization.JsonObjectContract.InvokeOnDeserializing方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。