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


C# Serialization.JsonContract类代码示例

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


JsonContract类属于Newtonsoft.Json.Serialization命名空间,在下文中一共展示了JsonContract类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Serialize

        public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
        {
            if (jsonWriter == null)
                throw new ArgumentNullException("jsonWriter");

            if (objectType != null)
                _rootContract = Serializer._contractResolver.ResolveContract(objectType);

            JsonContract contract = GetContractSafe(value);

            try
            {

                SerializeValue(jsonWriter, value, contract, null, null, null);
            }
            catch (Exception ex)
            {
                if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex))
                {
                    HandleError(jsonWriter, 0);
                }
                else
                {
                    // clear context in case serializer is being used inside a converter
                    // if the converter wraps the error then not clearing the context will cause this error:
                    // "Current error context error is different to requested error."
                    ClearErrorContext();
                    throw;
                }
            }
        }
开发者ID:rmblstrp,项目名称:Newtonsoft.Json,代码行数:31,代码来源:JsonSerializerInternalWriter.cs

示例2: Serialize

 // Token: 0x06000BEB RID: 3051
 // RVA: 0x0004663C File Offset: 0x0004483C
 public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
 {
     if (jsonWriter == null)
     {
         throw new ArgumentNullException("jsonWriter");
     }
     this._rootContract = ((objectType != null) ? this.Serializer._contractResolver.ResolveContract(objectType) : null);
     this._rootLevel = this._serializeStack.Count + 1;
     JsonContract contractSafe = this.GetContractSafe(value);
     try
     {
         this.SerializeValue(jsonWriter, value, contractSafe, null, null, null);
     }
     catch (Exception ex)
     {
         if (!base.IsErrorHandled(null, contractSafe, null, null, jsonWriter.Path, ex))
         {
             base.ClearErrorContext();
             throw;
         }
         this.HandleError(jsonWriter, 0);
     }
     finally
     {
         this._rootContract = null;
     }
 }
开发者ID:newchild,项目名称:Project-DayZero,代码行数:29,代码来源:JsonSerializerInternalWriter.cs

示例3: AddContractStackCallbacks

 private static void AddContractStackCallbacks (JsonContract contract)
 {
     contract.OnDeserializingCallbacks.Add((o, ctx) => JsonLinkedContext.Get(ctx).PushObject(o));
     contract.OnDeserializingCallbacks.Add((o, ctx) => JsonLinkedContext.Get(ctx).SetOwner(o));
     contract.OnDeserializedCallbacks.Add((o, ctx) => JsonLinkedContext.Get(ctx).PopObject(o));
     contract.OnSerializingCallbacks.Add((o, ctx) => JsonLinkedContext.Get(ctx).PushObject(o));
     contract.OnSerializedCallbacks.Add((o, ctx) => JsonLinkedContext.Get(ctx).PopObject(o));
 }
开发者ID:binki,项目名称:Alba.Framework,代码行数:8,代码来源:JsonLinkedContractResolver.cs

示例4: IsErrorHandled

    protected bool IsErrorHandled(object currentObject, JsonContract contract, object keyValue, Exception ex)
    {
      ErrorContext errorContext = GetErrorContext(currentObject, keyValue, ex);
      contract.InvokeOnError(currentObject, Serializer.Context, errorContext);

      if (!errorContext.Handled)
        Serializer.OnError(new ErrorEventArgs(currentObject, errorContext));

      return errorContext.Handled;
    }
开发者ID:runegri,项目名称:Applicable,代码行数:10,代码来源:JsonSerializerInternalBase.cs

示例5: SerializeValue

 private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
 {
   if (value == null)
   {
     writer.WriteNull();
   }
   else
   {
     JsonConverter converter;
     if (((converter = member != null ? member.Converter : (JsonConverter) null) != null || (converter = containerProperty != null ? containerProperty.ItemConverter : (JsonConverter) null) != null || ((converter = containerContract != null ? containerContract.ItemConverter : (JsonConverter) null) != null || (converter = valueContract.Converter) != null || ((converter = this.Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null || (converter = valueContract.InternalConverter) != null))) && converter.CanWrite)
     {
       this.SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
     }
     else
     {
       switch (valueContract.ContractType)
       {
         case JsonContractType.Object:
           this.SerializeObject(writer, value, (JsonObjectContract) valueContract, member, containerContract, containerProperty);
           break;
         case JsonContractType.Array:
           JsonArrayContract contract1 = (JsonArrayContract) valueContract;
           if (!contract1.IsMultidimensionalArray)
           {
             this.SerializeList(writer, contract1.CreateWrapper(value), contract1, member, containerContract, containerProperty);
             break;
           }
           else
           {
             this.SerializeMultidimensionalArray(writer, (Array) value, contract1, member, containerContract, containerProperty);
             break;
           }
         case JsonContractType.Primitive:
           this.SerializePrimitive(writer, value, (JsonPrimitiveContract) valueContract, member, containerContract, containerProperty);
           break;
         case JsonContractType.String:
           this.SerializeString(writer, value, (JsonStringContract) valueContract);
           break;
         case JsonContractType.Dictionary:
           JsonDictionaryContract contract2 = (JsonDictionaryContract) valueContract;
           this.SerializeDictionary(writer, contract2.CreateWrapper(value), contract2, member, containerContract, containerProperty);
           break;
         case JsonContractType.Serializable:
           this.SerializeISerializable(writer, (ISerializable) value, (JsonISerializableContract) valueContract, member, containerContract, containerProperty);
           break;
         case JsonContractType.Linq:
           ((JToken) value).WriteTo(writer, this.Serializer.Converters != null ? Enumerable.ToArray<JsonConverter>((IEnumerable<JsonConverter>) this.Serializer.Converters) : (JsonConverter[]) null);
           break;
       }
     }
   }
 }
开发者ID:Zeludon,项目名称:FEZ,代码行数:52,代码来源:JsonSerializerInternalWriter.cs

示例6: SerializeValue

    private void SerializeValue(JsonWriter writer, object value, JsonConverter memberConverter, JsonContract contract)
    {
      JsonConverter converter = memberConverter;

      if (value == null)
      {
        writer.WriteNull();
        return;
      }

      if (converter != null
          || ((converter = contract.Converter) != null)
          || Serializer.HasMatchingConverter(contract.UnderlyingType, out converter))
      {
        SerializeConvertable(writer, converter, value, contract);
      }
      else if (contract is JsonPrimitiveContract)
      {
        writer.WriteValue(value);
      }
      else if (value is JToken)
      {
        ((JToken) value).WriteTo(writer, (Serializer.Converters != null) ? Serializer.Converters.ToArray() : null);
      }
      else if (contract is JsonObjectContract)
      {
        SerializeObject(writer, value, (JsonObjectContract) contract);
      }
      else if (contract is JsonDictionaryContract)
      {
        SerializeDictionary(writer, (IDictionary) value, (JsonDictionaryContract) contract);
      }
      else if (contract is JsonArrayContract)
      {
        if (value is IList)
        {
          SerializeList(writer, (IList) value, (JsonArrayContract) contract);
        }
        else if (value is IEnumerable)
        {
          SerializeEnumerable(writer, (IEnumerable) value, (JsonArrayContract) contract);
        }
        else
        {
          throw new Exception(
            "Cannot serialize '{0}' into a JSON array. Type does not implement IEnumerable.".FormatWith(
              CultureInfo.InvariantCulture, value.GetType()));
        }
      }
    }
开发者ID:thirumg,项目名称:Avro.NET,代码行数:50,代码来源:JsonSerializerInternalWriter.cs

示例7: SerializePrimitive

    private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContract collectionValueContract)
    {
      if (contract.UnderlyingType == typeof (byte[]))
      {
        bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract);
        if (includeTypeDetails)
        {
          writer.WriteStartObject();
          WriteTypeProperty(writer, contract.CreatedType);
          writer.WritePropertyName(JsonTypeReflector.ValuePropertyName);
          writer.WriteValue(value);
          writer.WriteEndObject();
          return;
        }
      }

      writer.WriteValue(value);
    }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:18,代码来源:JsonSerializerInternalWriter.cs

示例8: Serialize

        public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
        {
            if (jsonWriter == null)
                throw new ArgumentNullException("jsonWriter");

            _rootContract = (objectType != null) ? Serializer._contractResolver.ResolveContract(objectType) : null;
            _rootLevel = _serializeStack.Count + 1;

            JsonContract contract = GetContractSafe(value);

            try
            {
                if (ShouldWriteReference(value, null, contract, null, null))
                {
                    WriteReference(jsonWriter, value);
                }
                else
                {
                    SerializeValue(jsonWriter, value, contract, null, null, null);
                }
            }
            catch (Exception ex)
            {
                if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex))
                {
                    HandleError(jsonWriter, 0);
                }
                else
                {
                    // clear context in case serializer is being used inside a converter
                    // if the converter wraps the error then not clearing the context will cause this error:
                    // "Current error context error is different to requested error."
                    ClearErrorContext();
                    throw;
                }
            }
            finally
            {
                // clear root contract to ensure that if level was > 1 then it won't
                // accidently be used for non root values
                _rootContract = null;
            }
        }
开发者ID:HaKDMoDz,项目名称:eStd,代码行数:43,代码来源:JsonSerializerInternalWriter.cs

示例9: ModifyContract

        public JsonContract ModifyContract(JsonContract contract)
        {
            if (contract is JsonDictionaryContract)
            {
                var dictionaryContract = contract as JsonDictionaryContract;
                if (typeof(GeoLocation).IsAssignableFrom(dictionaryContract.DictionaryValueType))
                {
                    dictionaryContract.PropertyNameResolver = x => x + "$$geo";
                }
                else if (typeof(Attachment).IsAssignableFrom(dictionaryContract.DictionaryValueType))
                {
                    dictionaryContract.PropertyNameResolver = x => x + "$$attachment";
                }
                else
                {
                    dictionaryContract.PropertyNameResolver = x => TypeSuffix.GetSuffixedFieldName(x, dictionaryContract.DictionaryValueType);
                }

                dictionaryContract.Converter = new DictionaryConverter() { PropertyNameDesolver = x => x.Contains('$') ? x.Split('$')[0] : x };
            }

            return contract;
        }
开发者ID:x2find,项目名称:Dictionary2Find,代码行数:23,代码来源:DictionaryInterceptor.cs

示例10: ShouldWriteType

    private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
    {
      TypeNameHandling resolvedTypeNameHandling =
        ((member != null) ? member.TypeNameHandling : null)
        ?? ((containerProperty != null) ? containerProperty.ItemTypeNameHandling : null)
        ?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null)
        ?? Serializer.TypeNameHandling;

      if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag))
        return true;

      // instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default)
      if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto))
      {
        if (member != null)
        {
          if (contract.UnderlyingType != member.PropertyContract.CreatedType)
            return true;
        }
        else if (containerContract != null && containerContract.ItemContract != null)
        {
          if (contract.UnderlyingType != containerContract.ItemContract.CreatedType)
            return true;
        }
      }

      return false;
    }
开发者ID:draptik,项目名称:RepoSync,代码行数:28,代码来源:JsonSerializerInternalWriter.cs

示例11: SerializeConvertable

    private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
    {
      if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty))
      {
        WriteReference(writer, value);
      }
      else
      {
        if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty))
          return;

        _serializeStack.Add(value);

        converter.WriteJson(writer, value, GetInternalSerializer());

        _serializeStack.RemoveAt(_serializeStack.Count - 1);
      }
    }
开发者ID:draptik,项目名称:RepoSync,代码行数:18,代码来源:JsonSerializerInternalWriter.cs

示例12: WriteObjectStart

    private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
    {
      writer.WriteStartObject();

      bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
      if (isReference)
      {
        writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
        writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, value));
      }
      if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty))
      {
        WriteTypeProperty(writer, contract.UnderlyingType);
      }
    }
开发者ID:draptik,项目名称:RepoSync,代码行数:15,代码来源:JsonSerializerInternalWriter.cs

示例13: CalculatePropertyValues

    private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue)
    {
      if (!property.Ignored && property.Readable && ShouldSerialize(property, value) && IsSpecified(property, value))
      {
        if (property.PropertyContract == null)
          property.PropertyContract = Serializer.ContractResolver.ResolveContract(property.PropertyType);

        memberValue = property.ValueProvider.GetValue(value);
        memberContract = (property.PropertyContract.UnderlyingType.IsSealed()) ? property.PropertyContract : GetContractSafe(memberValue);

        if (ShouldWriteProperty(memberValue, property))
        {
          if (ShouldWriteReference(memberValue, property, memberContract, contract, member))
          {
            writer.WritePropertyName(property.PropertyName);
            WriteReference(writer, memberValue);
            return false;
          }

          if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member))
            return false;

          if (memberValue == null)
          {
            JsonObjectContract objectContract = contract as JsonObjectContract;
            Required resolvedRequired = property._required ?? ((objectContract != null) ? objectContract.ItemRequired : null) ?? Required.Default;
            if (resolvedRequired == Required.Always)
              throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
          }

          return true;
        }
      }

      memberContract = null;
      memberValue = null;
      return false;
    }
开发者ID:draptik,项目名称:RepoSync,代码行数:38,代码来源:JsonSerializerInternalWriter.cs

示例14: CreateList

    private object CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, object existingValue, string reference)
    {
      object value;
      if (HasDefinedType(objectType))
      {
        JsonArrayContract arrayContract = EnsureArrayContract(reader, objectType, contract);

        if (existingValue == null)
          value = CreateAndPopulateList(reader, reference, arrayContract);
        else
          value = PopulateList(arrayContract.CreateWrapper(existingValue), reader, reference, arrayContract);
      }
      else
      {
        value = CreateJToken(reader, contract);
      }
      return value;
    }
开发者ID:bladefist,项目名称:Newtonsoft.Json,代码行数:18,代码来源:JsonSerializerInternalReader.cs

示例15: CreateObject

    private object CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, object existingValue)
    {
      CheckedRead(reader);

      string id = null;

      if (reader.TokenType == JsonToken.PropertyName)
      {
        string propertyName = reader.Value.ToString();

        if (propertyName.Length > 0 && propertyName[0] == '$')
        {
          // read 'special' properties
          // $type, $id, $ref, etc
          bool specialProperty;

          do
          {
            propertyName = reader.Value.ToString();

            if (string.Equals(propertyName, JsonTypeReflector.RefPropertyName, StringComparison.Ordinal))
            {
              CheckedRead(reader);
              if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null)
                throw CreateSerializationException(reader, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName));

              string reference = (reader.Value != null) ? reader.Value.ToString() : null;

              CheckedRead(reader);

              if (reference != null)
              {
                if (reader.TokenType == JsonToken.PropertyName)
                  throw CreateSerializationException(reader, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName));

                return Serializer.ReferenceResolver.ResolveReference(this, reference);
              }
              else
              {
                specialProperty = true;
              }
            }
            else if (string.Equals(propertyName, JsonTypeReflector.TypePropertyName, StringComparison.Ordinal))
            {
              CheckedRead(reader);
              string qualifiedTypeName = reader.Value.ToString();

              if ((((member != null) ? member.TypeNameHandling : null) ?? Serializer.TypeNameHandling) != TypeNameHandling.None)
              {
                string typeName;
                string assemblyName;
                ReflectionUtils.SplitFullyQualifiedTypeName(qualifiedTypeName, out typeName, out assemblyName);

                Type specifiedType;
                try
                {
                  specifiedType = Serializer.Binder.BindToType(assemblyName, typeName);
                }
                catch (Exception ex)
                {
                  throw CreateSerializationException(reader, "Error resolving type specified in JSON '{0}'.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName), ex);
                }

                if (specifiedType == null)
                  throw CreateSerializationException(reader, "Type specified in JSON '{0}' was not resolved.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName));

                if (objectType != null && !objectType.IsAssignableFrom(specifiedType))
                  throw CreateSerializationException(reader, "Type specified in JSON '{0}' is not compatible with '{1}'.".FormatWith(CultureInfo.InvariantCulture, specifiedType.AssemblyQualifiedName, objectType.AssemblyQualifiedName));

                objectType = specifiedType;
                contract = GetContractSafe(specifiedType);
              }

              CheckedRead(reader);

              specialProperty = true;
            }
            else if (string.Equals(propertyName, JsonTypeReflector.IdPropertyName, StringComparison.Ordinal))
            {
              CheckedRead(reader);

              id = (reader.Value != null) ? reader.Value.ToString() : null;

              CheckedRead(reader);
              specialProperty = true;
            }
            else if (string.Equals(propertyName, JsonTypeReflector.ArrayValuesPropertyName, StringComparison.Ordinal))
            {
              CheckedRead(reader);
              object list = CreateList(reader, objectType, contract, member, existingValue, id);
              CheckedRead(reader);
              return list;
            }
            else
            {
              specialProperty = false;
            }
          } while (specialProperty
                   && reader.TokenType == JsonToken.PropertyName);
        }
//.........这里部分代码省略.........
开发者ID:bladefist,项目名称:Newtonsoft.Json,代码行数:101,代码来源:JsonSerializerInternalReader.cs


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