Maps a JSON property to a .NET member or constructor parameter.
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
    public override void WriteJson(JsonWriter writer, JsonProperty property, object value, JsonSerializer serializer)
    {
      string text;

      if (value is DateTime)
      {
        DateTime dateTime = (DateTime)value;

        if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
          || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
          dateTime = dateTime.ToUniversalTime();

        text = dateTime.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
      }
#if !PocketPC && !NET20
      else if (value is DateTimeOffset)
      {
        DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
        if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
          || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
          dateTimeOffset = dateTimeOffset.ToUniversalTime();

        text = dateTimeOffset.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
      }
#endif
      else
      {
        throw new Exception("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)));
      }

      writer.WriteValue(text);
    }
        public static Schema WithValidationProperties(this Schema schema, JsonProperty jsonProperty)
        {
            var propInfo = jsonProperty.PropertyInfo();
            if (propInfo == null)
                return schema;

            foreach (var attribute in propInfo.GetCustomAttributes(false))
            {
                var regex = attribute as RegularExpressionAttribute;
                if (regex != null)
                    schema.pattern = regex.Pattern;

                var range = attribute as RangeAttribute;
                if (range != null)
                {
                    int maximum;
                    if (Int32.TryParse(range.Maximum.ToString(), out maximum))
                        schema.maximum = maximum;

                    int minimum;
                    if (Int32.TryParse(range.Minimum.ToString(), out minimum))
                        schema.minimum = minimum;
                }
            }

            if (!jsonProperty.Writable)
                schema.readOnly = true;

            return schema;
        }
        /// <summary>
        /// Ensures that enum values are serialized as camel-cased strings.
        /// </summary>
        private static JsonProperty CamelCaseEnumValues(JsonProperty property)
        {
            if (property.PropertyType.GetTypeInfo().IsEnum)
                property.Converter = new StringEnumConverter(camelCaseText: true);

            return property;
        }
      public override object ReadJson(JsonReader reader, Type objectType, JsonProperty member, object existingValue, JsonSerializer serializer)
    {
      NameContainer nameContainer = new NameContainer();
      nameContainer.Value = (string)reader.Value;

      return nameContainer;
    }
    /// <summary>
    /// Determines whether this instance can convert the specified object type.
    /// </summary>
    /// <param name="objectType">Type of the object.</param>
    /// <returns>
    /// 	<c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
    /// </returns>
      public override bool CanConvert(Type objectType, JsonProperty property)
    {
      if (objectType.IsValueType && objectType.IsGenericType)
        return (objectType.GetGenericTypeDefinition() == typeof (KeyValuePair<,>));

      return false;
    }
 // Token: 0x06000BDB RID: 3035
 // RVA: 0x00046004 File Offset: 0x00044204
 public object CreateNewObject(JsonReader reader, JsonObjectContract objectContract, JsonProperty containerMember, JsonProperty containerProperty, string id, out bool createdFromNonDefaultCreator)
 {
     object obj = null;
     if (objectContract.OverrideCreator != null)
     {
         if (objectContract.CreatorParameters.Count > 0)
         {
             createdFromNonDefaultCreator = true;
             return this.CreateObjectUsingCreatorWithParameters(reader, objectContract, containerMember, objectContract.OverrideCreator, id);
         }
         obj = objectContract.OverrideCreator(new object[0]);
     }
     else if (objectContract.DefaultCreator != null && (!objectContract.DefaultCreatorNonPublic || this.Serializer._constructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor || objectContract.ParametrizedCreator == null))
     {
         obj = objectContract.DefaultCreator();
     }
     else if (objectContract.ParametrizedCreator != null)
     {
         createdFromNonDefaultCreator = true;
         return this.CreateObjectUsingCreatorWithParameters(reader, objectContract, containerMember, objectContract.ParametrizedCreator, id);
     }
     if (obj != null)
     {
         createdFromNonDefaultCreator = false;
         return obj;
     }
     if (!objectContract.IsInstantiable)
     {
         throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantiated.", CultureInfo.InvariantCulture, objectContract.UnderlyingType));
     }
     throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Unable to find a constructor to use for type {0}. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.", CultureInfo.InvariantCulture, objectContract.UnderlyingType));
 }
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
    public override void WriteJson(JsonWriter writer, JsonProperty property, object value, JsonSerializer serializer)
    {
      IEntityKeyMember entityKeyMember = DynamicWrapper.CreateWrapper<IEntityKeyMember>(value);
      Type keyType = (entityKeyMember.Value != null) ? entityKeyMember.Value.GetType() : null;

      writer.WriteStartObject();
      writer.WritePropertyName("Key");
      writer.WriteValue(entityKeyMember.Key);
      writer.WritePropertyName("Type");
      writer.WriteValue((keyType != null) ? keyType.FullName : null);

      writer.WritePropertyName("Value");

      if (keyType != null)
      {
        string valueJson;
        if (JsonSerializerInternalWriter.TryConvertToString(entityKeyMember.Value, keyType, out valueJson))
          writer.WriteValue(valueJson);
        else
          writer.WriteValue(entityKeyMember.Value);
      }
      else
      {
        writer.WriteNull();
      }

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

          if (contract.IsNullable)
            writer.WriteValue(value, true);
          else
            writer.WriteValue(value);

          writer.WriteEndObject();
          return;
        }
      }

      if (contract.IsNullable)
        writer.WriteValue(value, true);
      else
        writer.WriteValue(value);
    }
        /// <summary>
        /// Check if a property implements IEnumerable and IEnumerable&lt;&gt;
        /// </summary>
        private static bool IsEnumerable(JsonProperty property)
        {
            if (property.PropertyType == typeof (string))
                return false;

            var interfaces = property.PropertyType.GetInterfaces();
            return interfaces.Any(i => i == typeof(IEnumerable));
        }
    public override void WriteJson(JsonWriter writer, JsonProperty member, object value, JsonSerializer serializer)
    {
      ConverterPrecedenceClass c = (ConverterPrecedenceClass)value;

      JToken j = new JArray(ConverterType, c.TestValue);

      j.WriteTo(writer);
    }
 /// <summary>
 /// Initializes a new instance of the <see cref="JSchemaTypeGenerationContext"/> class.
 /// </summary>
 /// <param name="objectType">The object type.</param>
 /// <param name="required">The required state.</param>
 /// <param name="memberProperty">The member property.</param>
 /// <param name="parentContract">The parent contract.</param>
 /// <param name="generator">The current <see cref="JSchemaGenerator"/>.</param>
 public JSchemaTypeGenerationContext(Type objectType, Required required, JsonProperty memberProperty, JsonContainerContract parentContract, JSchemaGenerator generator)
 {
     _objectType = objectType;
     _required = required;
     _memberProperty = memberProperty;
     _parentContract = parentContract;
     _generator = generator;
 }
        private bool IsNotEmpty(JsonProperty property, object target)
        {
            var value = property.ValueProvider.GetValue(target) as IEnumerable<object>;
            if (value != null)
                return value.Count() != 0;

            return true;
        }
    /// <summary>
    /// Reads the JSON representation of the object.
    /// </summary>
    /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
    /// <param name="objectType">Type of the object.</param>
    /// <param name="existingValue">The existing value of object being read.</param>
    /// <param name="serializer">The calling serializer.</param>
    /// <returns>The object value.</returns>
      public override object ReadJson(JsonReader reader, Type objectType, JsonProperty property, object existingValue, JsonSerializer serializer)
    {
      if (reader.TokenType != JsonToken.Bytes)
        throw new JsonSerializationException("Expected Bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));

      byte[] value = (byte[])reader.Value;

      return new BsonObjectId(value);
    }
      public override void WriteJson(JsonWriter writer, JsonProperty member, object value, JsonSerializer serializer)
    {
      NameContainer nameContainer = value as NameContainer;

      if (nameContainer != null)
        writer.WriteValue(nameContainer.Value);
      else
        writer.WriteNull();
    }
      public override void WriteJson(JsonWriter writer, JsonProperty member, object value, JsonSerializer serializer)
    {
      Department department = (Department)value;

      JObject o = new JObject();
      o["DepartmentId"] = new JValue(department.DepartmentId.ToString());
      o["Name"] = new JValue(new string(department.Name.Reverse().ToArray()));

      o.WriteTo(writer);
    }
      public override object ReadJson(JsonReader reader, Type objectType, JsonProperty member, object existingValue, JsonSerializer serializer)
    {
      JObject o = JObject.Load(reader);

      Department department = new Department();
      department.DepartmentId = new Guid((string)o["DepartmentId"]);
      department.Name = new string(((string) o["Name"]).Reverse().ToArray());

      return department;
    }
        /// <summary>Gets the converted property name.</summary>
        /// <param name="property">The property.</param>
        /// <param name="memberInfo">The member info.</param>
        /// <returns>The property name.</returns>
        public virtual string GetPropertyName(Newtonsoft.Json.Serialization.JsonProperty property, MemberInfo memberInfo)
        {
            var propertyName = memberInfo != null?ReflectionCache.GetPropertiesAndFields(memberInfo.DeclaringType)
                               .First(p => p.MemberInfo.Name == memberInfo.Name).GetName() : property.PropertyName;

            var contractResolver = Settings.ActualContractResolver as DefaultContractResolver;

            return(contractResolver != null
                ? contractResolver.GetResolvedPropertyName(propertyName)
                : propertyName);
        }
		protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
		{
			var list = base.CreateProperties(type, memberSerialization);

			// add events as json properties
			foreach (var eventInfo in type.GetRuntimeEvents().Where(r => 
			{
				var addMethod = r.GetAddMethod();
				return addMethod.IsPublic && !addMethod.IsStatic 
					&& (
						(
							#if PCL
							r.EventHandlerType.GetTypeInfo().IsGenericType
							#else
							r.EventHandlerType.IsGenericType
							#endif
							&& r.EventHandlerType.GetGenericTypeDefinition() == typeof(EventHandler<>)
						)
						|| r.EventHandlerType == typeof(EventHandler)
					);
			}))
			{
				var prop = new JsonProperty
				{
					PropertyName = ResolvePropertyName(eventInfo.Name),
					DeclaringType = eventInfo.DeclaringType,
					PropertyType = eventInfo.EventHandlerType,
					ValueProvider = CreateMemberValueProvider(eventInfo),
					Writable = true
				};
				list.Add(prop);
			}

			var idprop = type.GetRuntimeProperty("ID");
			if (idprop != null)
			{
				var prop = CreateProperty(idprop, memberSerialization);
				prop.PropertyName = "$name";
				prop.PropertyType = typeof(NameConverter.Info);
				prop.MemberConverter = new NameConverter();
				prop.ValueProvider = new NameConverter.ValueProvider();
				list.Add(prop);
			}

			if (list.All(r => r.PropertyName != "$type"))
			{
				var prop = new JsonProperty();
				prop.PropertyName = "$type";
				prop.Ignored = true;
				list.Add(prop);
			}

			return list;
		}
    public override object ReadJson(JsonReader reader, Type objectType, JsonProperty member, object existingValue, JsonSerializer serializer)
    {
      JToken j = JArray.Load(reader);

      string converter = (string)j[0];
      if (converter != ConverterType)
        throw new Exception(StringUtils.FormatWith("Serialize converter {0} and deserialize converter {1} do not match.", CultureInfo.InvariantCulture, converter, ConverterType));

      string testValue = (string)j[1];
      return new ConverterPrecedenceClass(testValue);
    }
        /// <summary>
        /// Initializes a new instance.
        /// </summary>
        public JsonPatchProperty(JsonProperty property, object parent)
        {
            if (property == null)
                throw new ArgumentNullException("property");

            if (parent == null)
                throw new ArgumentNullException("parent");

            Property = property;
            Parent = parent;
        }
    /// <summary>
    /// Determines whether this instance can convert the specified object type.
    /// </summary>
    /// <param name="objectType">Type of the object.</param>
    /// <returns>
    /// 	<c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
    /// </returns>
      public override bool CanConvert(Type objectType, JsonProperty property)
    {
      if (objectType == typeof(DateTime) || objectType == typeof(DateTime?))
        return true;
#if !PocketPC && !NET20
      if (objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?))
        return true;
#endif

      return false;
    }
 private bool ShouldInclude(JsonProperty jsonProperty)
 {
     if ((jsonProperty.PropertyType.IsClass || jsonProperty.PropertyType.IsInterface) && 
         jsonProperty.PropertyType != typeof(string))
     {
         if (includes.Any(y => y.Contains(jsonProperty.PropertyName)))
             return true;
         return false;
     }
     return true;
 }
 JsonProperty GetJsonProperty(Type type, JsonProperty mappedProperty, SensitiveDataAttribute attribute)
 {
     return new JsonProperty()
     {
         DeclaringType = type,
         PropertyName = GetEmittedPropertyName(mappedProperty, attribute),
         UnderlyingName = mappedProperty.UnderlyingName,
         PropertyType = typeof(string),
         ValueProvider = new SensitiveDataValueProvider(mappedProperty.UnderlyingName, SaltGenerator),
         Readable = true,
     };
 }
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
    public override void WriteJson(JsonWriter writer, JsonProperty property, object value, JsonSerializer serializer)
    {
      if (value == null)
      {
        writer.WriteNull();
        return;
      }

      byte[] data = GetByteArray(value);

      writer.WriteValue(data);
    }
    static bool IsSagaProperty(JsonProperty jsonProperty)
    {
        var declaringType = jsonProperty.DeclaringType;
        if (!declaringType.IsAssignableFrom(typeof(IContainSagaData)))
        {
            return false;
        }

        return declaringType
            .GetInterfaceMap(typeof(IContainSagaData))
            .InterfaceMethods.Any(info => jsonProperty.UnderlyingName == info.Name);
    }
 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;
       }
     }
   }
 }
 // Determines whether a member is required or not and sets the appropriate JsonProperty settings
 private void ConfigureProperty(MemberInfo member, JsonProperty property)
 {
     if (_formatter.RequiredMemberSelector != null && _formatter.RequiredMemberSelector.IsRequiredMember(member))
     {
         property.Required = Required.AllowNull;
         property.DefaultValueHandling = DefaultValueHandling.Include;
         property.NullValueHandling = NullValueHandling.Include;
     }
     else
     {
         property.Required = Required.Default;
     }
 }
 private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
 {
   if (contract.UnderlyingType == typeof (byte[]) && this.ShouldWriteType(TypeNameHandling.Objects, (JsonContract) contract, member, containerContract, containerProperty))
   {
     writer.WriteStartObject();
     this.WriteTypeProperty(writer, contract.CreatedType);
     writer.WritePropertyName("$value");
     writer.WriteValue(value);
     writer.WriteEndObject();
   }
   else
     writer.WriteValue(value);
 }
        private static bool IsPropertyUpdateable(Type type, JsonProperty property)
        {
            var isUpdateable = true;
            var propInfo = type.GetRuntimeProperty(property.PropertyName);

            if (propInfo != null)
            {
                var updateableAttr = propInfo.GetCustomAttribute(typeof(UpdateableAttribute), false);
                isUpdateable = updateableAttr == null || ((UpdateableAttribute)updateableAttr).Updateable;
            }

            return isUpdateable;
        }
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
      public override void WriteJson(JsonWriter writer, JsonProperty property, object value, JsonSerializer serializer)
    {
      Type t = value.GetType();
      PropertyInfo keyProperty = t.GetProperty("Key");
      PropertyInfo valueProperty = t.GetProperty("Value");

      writer.WriteStartObject();
      writer.WritePropertyName("Key");
      serializer.Serialize(writer, ReflectionUtils.GetMemberValue(keyProperty, value));
      writer.WritePropertyName("Value");
      serializer.Serialize(writer, ReflectionUtils.GetMemberValue(valueProperty, value));
      writer.WriteEndObject();
    }
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
      public override void WriteJson(JsonWriter writer, JsonProperty property, object value, JsonSerializer serializer)
    {
      BsonObjectId objectId = (BsonObjectId) value;

      BsonWriter bsonWriter = writer as BsonWriter;
      if (bsonWriter != null)
      {
        bsonWriter.WriteObjectId(objectId.Value);
      }
      else
      {
        writer.WriteValue(objectId.Value);
      }
    }
Exemple #32
0
            /// <inheritdoc />
            public JsonContract ResolveContract(Type type)
            {
                JsonContract jsonContract = _defaultContractResolver.ResolveContract(type);

                if (type.IsAssignableTo <IMetadataSchemaProvider>() && jsonContract is JsonObjectContract contract)
                {
                    JsonObjectContract schemaProviderContract = (JsonObjectContract)_defaultContractResolver.ResolveContract(typeof(IMetadataSchemaProvider));
                    JsonProperty       jsonProperty           = schemaProviderContract.Properties[0];
                    jsonProperty.PropertyName = "$defs";
                    contract.Properties.AddProperty(jsonProperty);
                }

                return(jsonContract);
            }
Exemple #33
0
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty prop     = base.CreateProperty(member, memberSerialization);
            var          propInfo = member as PropertyInfo;

            if (propInfo != null)
            {
                if (propInfo.GetMethod.IsVirtual && !propInfo.GetMethod.IsFinal)
                {
                    prop.ShouldSerialize = obj => false;
                }
            }
            return(prop);
        }
Exemple #34
0
 private object ConvertDefaultValue(Newtonsoft.Json.Serialization.JsonProperty property)
 {
     if (property.DefaultValue != null && property.DefaultValue.GetType().GetTypeInfo().IsEnum)
     {
         var hasStringEnumConverter = typeof(StringEnumConverter).GetTypeInfo().IsAssignableFrom(property.Converter?.GetType().GetTypeInfo());
         if (hasStringEnumConverter)
         {
             return(property.DefaultValue.ToString());
         }
         else
         {
             return((int)property.DefaultValue);
         }
     }
     else
     {
         return(property.DefaultValue);
     }
 }
Exemple #35
0
        /// <summary>Gets the converted property name.</summary>
        /// <param name="property">The property.</param>
        /// <param name="memberInfo">The member info.</param>
        /// <returns>The property name.</returns>
        public virtual string GetPropertyName(Newtonsoft.Json.Serialization.JsonProperty property, MemberInfo memberInfo)
        {
            try
            {
                var propertyName = memberInfo != null?ReflectionCache.GetPropertiesAndFields(memberInfo.DeclaringType)
                                   .First(p => p.MemberInfo.Name == memberInfo.Name).GetName() : property.PropertyName;

                var contractResolver = Settings.ActualContractResolver as DefaultContractResolver;
                return(contractResolver != null
                    ? contractResolver.GetResolvedPropertyName(propertyName)
                    : propertyName);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Could not get JSON property name of property '" +
                                                    (memberInfo != null ? memberInfo.Name : "n/a") + "' and type '" +
                                                    (memberInfo?.DeclaringType != null ? memberInfo.DeclaringType.FullName : "n/a") + "'.", e);
            }
        }
        private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            IWrappedDictionary wrappedDictionary    = values as IWrappedDictionary;
            object             underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values;

            OnSerializing(writer, contract, underlyingDictionary);
            _serializeStack.Add(underlyingDictionary);

            WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);

            if (contract.ItemContract == null)
            {
                contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
            }

            if (contract.KeyContract == null)
            {
                contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
            }

            int initialDepth = writer.Top;

            foreach (DictionaryEntry entry in values)
            {
                bool   escape;
                string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape);

                propertyName = (contract.DictionaryKeyResolver != null)
                    ? contract.DictionaryKeyResolver(propertyName)
                    : propertyName;

                try
                {
                    object       value         = entry.Value;
                    JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);

                    if (ShouldWriteReference(value, null, valueContract, contract, member))
                    {
                        writer.WritePropertyName(propertyName, escape);
                        WriteReference(writer, value);
                    }
                    else
                    {
                        if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
                        {
                            continue;
                        }

                        writer.WritePropertyName(propertyName, escape);

                        SerializeValue(writer, value, valueContract, null, contract, member);
                    }
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
                    {
                        HandleError(writer, initialDepth);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            writer.WriteEndObject();

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            OnSerialized(writer, contract, underlyingDictionary);
        }
        private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            OnSerializing(writer, contract, value);

            _serializeStack.Add(value);

            WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);

            int initialDepth = writer.Top;

            for (int index = 0; index < contract.Properties.Count; index++)
            {
                JsonProperty property = contract.Properties[index];
                try
                {
                    if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue))
                    {
                        continue;
                    }

                    property.WritePropertyName(writer);
                    SerializeValue(writer, memberValue, memberContract, property, contract, member);
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
                    {
                        HandleError(writer, initialDepth);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            IEnumerable <KeyValuePair <object, object> > extensionData = contract.ExtensionDataGetter?.Invoke(value);

            if (extensionData != null)
            {
                foreach (KeyValuePair <object, object> e in extensionData)
                {
                    JsonContract keyContract   = GetContractSafe(e.Key);
                    JsonContract valueContract = GetContractSafe(e.Value);

                    string propertyName = GetPropertyName(writer, e.Key, keyContract, out _);

                    propertyName = (contract.ExtensionDataNameResolver != null)
                        ? contract.ExtensionDataNameResolver(propertyName)
                        : propertyName;

                    if (ShouldWriteReference(e.Value, null, valueContract, contract, member))
                    {
                        writer.WritePropertyName(propertyName);
                        WriteReference(writer, e.Value);
                    }
                    else
                    {
                        if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member))
                        {
                            continue;
                        }

                        writer.WritePropertyName(propertyName);

                        SerializeValue(writer, e.Value, valueContract, null, contract, member);
                    }
                }
            }

            writer.WriteEndObject();

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            OnSerialized(writer, contract, value);
        }
        private bool?ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            bool?isReference = null;

            // value could be coming from a dictionary or array and not have a property
            if (property != null)
            {
                isReference = property.IsReference;
            }

            if (isReference == null && containerProperty != null)
            {
                isReference = containerProperty.ItemIsReference;
            }

            if (isReference == null && collectionContract != null)
            {
                isReference = collectionContract.ItemIsReference;
            }

            if (isReference == null)
            {
                isReference = contract.IsReference;
            }

            return(isReference);
        }
        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(writer, property, value) && IsSpecified(writer, property, value))
            {
                if (property.PropertyContract == null)
                {
                    property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType);
                }

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

                if (ShouldWriteProperty(memberValue, contract as JsonObjectContract, property))
                {
                    if (ShouldWriteReference(memberValue, property, memberContract, contract, member))
                    {
                        property.WritePropertyName(writer);
                        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?.ItemRequired ?? 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);
                        }
                        if (resolvedRequired == Required.DisallowNull)
                        {
                            throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a non-null value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
                        }
                    }

                    return(true);
                }
            }

            memberContract = null;
            memberValue    = null;
            return(false);
        }
        private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
        {
            if (contract.TypeCode == PrimitiveTypeCode.Bytes)
            {
                // if type name handling is enabled then wrap the base64 byte string in an object with the type name
                bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty);
                if (includeTypeDetails)
                {
                    writer.WriteStartObject();
                    WriteTypeProperty(writer, contract.CreatedType);
                    writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false);

                    JsonWriter.WriteValue(writer, contract.TypeCode, value);

                    writer.WriteEndObject();
                    return;
                }
            }

            JsonWriter.WriteValue(writer, contract.TypeCode, value);
        }
Exemple #41
0
        private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            if (!JsonTypeReflector.FullyTrusted)
            {
                string message = @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine +
                                 @"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
                message = message.FormatWith(CultureInfo.InvariantCulture, value.GetType());

                throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
            }

            OnSerializing(writer, contract, value);
            _serializeStack.Add(value);

            WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);

            SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());

            value.GetObjectData(serializationInfo, Serializer._context);

            foreach (SerializationEntry serializationEntry in serializationInfo)
            {
                JsonContract valueContract = GetContractSafe(serializationEntry.Value);

                if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member))
                {
                    writer.WritePropertyName(serializationEntry.Name);
                    WriteReference(writer, serializationEntry.Value);
                }
                else if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member))
                {
                    writer.WritePropertyName(serializationEntry.Name);
                    SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member);
                }
            }

            writer.WriteEndObject();

            _serializeStack.RemoveAt(_serializeStack.Count - 1);
            OnSerialized(writer, contract, value);
        }
        private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            object underlyingList = values is IWrappedCollection wrappedCollection ? wrappedCollection.UnderlyingCollection : values;

            OnSerializing(writer, contract, underlyingList);

            _serializeStack.Add(underlyingList);

            bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty);

            writer.WriteStartArray();

            int initialDepth = writer.Top;

            int index = 0;

            // note that an error in the IEnumerable won't be caught
            foreach (object value in values)
            {
                try
                {
                    JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);

                    if (ShouldWriteReference(value, null, valueContract, contract, member))
                    {
                        WriteReference(writer, value);
                    }
                    else
                    {
                        if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
                        {
                            SerializeValue(writer, value, valueContract, null, contract, member);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex))
                    {
                        HandleError(writer, initialDepth);
                    }
                    else
                    {
                        throw;
                    }
                }
                finally
                {
                    index++;
                }
            }

            writer.WriteEndArray();

            if (hasWrittenMetadataObject)
            {
                writer.WriteEndObject();
            }

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            OnSerialized(writer, contract, underlyingList);
        }
        /// <summary>Applies the property annotations to the JSON property.</summary>
        /// <param name="jsonProperty">The JSON property.</param>
        /// <param name="property"></param>
        /// <param name="parentType">The type of the parent.</param>
        /// <param name="attributes">The attributes.</param>
        /// <param name="propertyTypeDescription">The property type description.</param>
        public void ApplyPropertyAnnotations(JsonSchema4 jsonProperty, Newtonsoft.Json.Serialization.JsonProperty property, Type parentType, IEnumerable <Attribute> attributes, JsonObjectTypeDescription propertyTypeDescription)
        {
            // TODO: Refactor out

            dynamic displayAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.DisplayAttribute");

            if (displayAttribute != null && displayAttribute.Name != null)
            {
                jsonProperty.Title = displayAttribute.Name;
            }

            if (property != null)
            {
                jsonProperty.Default = ConvertDefaultValue(property);
            }
            else
            {
                dynamic defaultValueAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DefaultValueAttribute");
                if (defaultValueAttribute != null)
                {
                    jsonProperty.Default = defaultValueAttribute.Value;
                }
            }

            dynamic regexAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.RegularExpressionAttribute");

            if (regexAttribute != null)
            {
                jsonProperty.Pattern = regexAttribute.Pattern;
            }

            if (propertyTypeDescription.Type == JsonObjectType.Number ||
                propertyTypeDescription.Type == JsonObjectType.Integer)
            {
                dynamic rangeAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.RangeAttribute");
                if (rangeAttribute != null)
                {
                    if (rangeAttribute.Minimum != null && rangeAttribute.Minimum > double.MinValue)
                    {
                        jsonProperty.Minimum = (decimal?)(double)rangeAttribute.Minimum;
                    }
                    if (rangeAttribute.Maximum != null && rangeAttribute.Maximum < double.MaxValue)
                    {
                        jsonProperty.Maximum = (decimal?)(double)rangeAttribute.Maximum;
                    }
                }

                var multipleOfAttribute = attributes.OfType <MultipleOfAttribute>().SingleOrDefault();
                if (multipleOfAttribute != null)
                {
                    jsonProperty.MultipleOf = multipleOfAttribute.MultipleOf;
                }
            }

            dynamic minLengthAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.MinLengthAttribute");

            if (minLengthAttribute != null && minLengthAttribute.Length != null)
            {
                if (propertyTypeDescription.Type == JsonObjectType.String)
                {
                    jsonProperty.MinLength = minLengthAttribute.Length;
                }
                else if (propertyTypeDescription.Type == JsonObjectType.Array)
                {
                    jsonProperty.MinItems = minLengthAttribute.Length;
                }
            }

            dynamic maxLengthAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.MaxLengthAttribute");

            if (maxLengthAttribute != null && maxLengthAttribute.Length != null)
            {
                if (propertyTypeDescription.Type == JsonObjectType.String)
                {
                    jsonProperty.MaxLength = maxLengthAttribute.Length;
                }
                else if (propertyTypeDescription.Type == JsonObjectType.Array)
                {
                    jsonProperty.MaxItems = maxLengthAttribute.Length;
                }
            }

            dynamic stringLengthAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.StringLengthAttribute");

            if (stringLengthAttribute != null)
            {
                if (propertyTypeDescription.Type == JsonObjectType.String)
                {
                    jsonProperty.MinLength = stringLengthAttribute.MinimumLength;
                    jsonProperty.MaxLength = stringLengthAttribute.MaximumLength;
                }
            }

            dynamic dataTypeAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.DataTypeAttribute");

            if (dataTypeAttribute != null)
            {
                var dataType = dataTypeAttribute.DataType.ToString();
                if (DataTypeFormats.ContainsKey(dataType))
                {
                    jsonProperty.Format = DataTypeFormats[dataType];
                }
            }
        }
        private bool ShouldWriteProperty(object memberValue, JsonObjectContract containerContract, JsonProperty property)
        {
            if (memberValue == null && ResolvedNullValueHandling(containerContract, property) == NullValueHandling.Ignore)
            {
                return(false);
            }

            if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore) &&
                MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue()))
            {
                return(false);
            }

            return(true);
        }
Exemple #45
0
        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);
        }
        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);

            // don't make readonly fields that aren't creator parameters the referenced value because they can't be deserialized to
            if (isReference && (member == null || member.Writable || HasCreatorParameter(collectionContract, member)))
            {
                WriteReferenceIdProperty(writer, contract.UnderlyingType, value);
            }
            if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty))
            {
                WriteTypeProperty(writer, contract.UnderlyingType);
            }
        }
        private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            OnSerializing(writer, contract, values);

            _serializeStack.Add(values);

            bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty);

            SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, CollectionUtils.ArrayEmpty <int>());

            if (hasWrittenMetadataObject)
            {
                writer.WriteEndObject();
            }

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            OnSerialized(writer, contract, values);
        }
        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);

                if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
                {
                    TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
                }

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

                if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
                {
                    TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
                }

                _serializeStack.RemoveAt(_serializeStack.Count - 1);
            }
        }
Exemple #49
0
        private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
        {
            TypeNameHandling resolvedTypeNameHandling =
                member?.TypeNameHandling
                ?? containerProperty?.ItemTypeNameHandling
                ?? containerContract?.ItemTypeNameHandling
                ?? 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.NonNullableUnderlyingType != member.PropertyContract.CreatedType)
                    {
                        return(true);
                    }
                }
                else if (containerContract != null)
                {
                    if (containerContract.ItemContract == null || contract.NonNullableUnderlyingType != containerContract.ItemContract.CreatedType)
                    {
                        return(true);
                    }
                }
                else if (_rootType != null && _serializeStack.Count == _rootLevel)
                {
                    JsonContract rootContract = Serializer._contractResolver.ResolveContract(_rootType);

                    if (contract.NonNullableUnderlyingType != rootContract.CreatedType)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
        private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            object underlyingDictionary = values is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : values;

            OnSerializing(writer, contract, underlyingDictionary);
            _serializeStack.Add(underlyingDictionary);

            WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);

            if (contract.ItemContract == null)
            {
                contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
            }

            if (contract.KeyContract == null)
            {
                contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
            }

            int initialDepth = writer.Top;

            // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
            IDictionaryEnumerator e = values.GetEnumerator();

            try
            {
                while (e.MoveNext())
                {
                    DictionaryEntry entry = e.Entry;

                    string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out bool escape);

                    propertyName = (contract.DictionaryKeyResolver != null)
                        ? contract.DictionaryKeyResolver(propertyName)
                        : propertyName;

                    try
                    {
                        object       value         = entry.Value;
                        JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);

                        if (ShouldWriteReference(value, null, valueContract, contract, member))
                        {
                            writer.WritePropertyName(propertyName, escape);
                            WriteReference(writer, value);
                        }
                        else
                        {
                            if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
                            {
                                continue;
                            }

                            writer.WritePropertyName(propertyName, escape);

                            SerializeValue(writer, value, valueContract, null, contract, member);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
                        {
                            HandleError(writer, initialDepth);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
            finally
            {
                (e as IDisposable)?.Dispose();
            }

            writer.WriteEndObject();

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            OnSerialized(writer, contract, underlyingDictionary);
        }
        private async Task LoadPropertyOrFieldAsync(Newtonsoft.Json.Serialization.JsonProperty property, MemberInfo propertyInfo, Type parentType, JsonSchema4 parentSchema, JsonSchemaResolver schemaResolver)
        {
            var propertyType            = property.PropertyType;
            var attributes              = property.AttributeProvider.GetAttributes(true).ToArray();
            var propertyTypeDescription = JsonObjectTypeDescription.FromType(propertyType, ResolveContract(propertyType), null, Settings.DefaultEnumHandling);

            if (property.Ignored == false)
            {
                JsonProperty jsonProperty;

                if (propertyType.Name == "Nullable`1")
#if !LEGACY
                { propertyType = propertyType.GenericTypeArguments[0]; }
#else
                { propertyType = propertyType.GetGenericArguments()[0]; }
#endif

                var requiresSchemaReference = RequiresSchemaReference(propertyType, attributes);
                if (requiresSchemaReference)
                {
                    var propertySchema = await GenerateAsync(propertyType, attributes, schemaResolver).ConfigureAwait(false);

                    // The schema is automatically added to Definitions if it is missing in JsonPathUtilities.GetJsonPath()
                    if (Settings.NullHandling == NullHandling.JsonSchema)
                    {
                        jsonProperty = new JsonProperty();
                        jsonProperty.OneOf.Add(new JsonSchema4
                        {
                            SchemaReference = propertySchema.ActualSchema
                        });
                    }
                    else
                    {
                        jsonProperty = new JsonProperty
                        {
                            SchemaReference = propertySchema.ActualSchema
                        };
                    }
                }
                else
                {
                    jsonProperty = await GenerateAsync <JsonProperty>(propertyType, attributes, schemaResolver).ConfigureAwait(false);
                }

                var contractResolver = Settings.ActualContractResolver as DefaultContractResolver;
                var propertyName     = contractResolver != null?
                                       contractResolver.GetResolvedPropertyName(property.PropertyName) :
                                           property.PropertyName;

                if (parentSchema.Properties.ContainsKey(propertyName))
                {
                    throw new InvalidOperationException("The JSON property '" + propertyName + "' is defined multiple times on type '" + parentType.FullName + "'.");
                }

                if (Settings.GenerateXmlObjects)
                {
                    jsonProperty.GenerateXmlObjectForProperty(parentType, propertyName, attributes);
                }

                parentSchema.Properties.Add(propertyName, jsonProperty);

                var requiredAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.RequiredAttribute");

                var hasJsonNetAttributeRequired  = property.Required == Required.Always || property.Required == Required.AllowNull;
                var isDataContractMemberRequired = GetDataMemberAttribute(parentType, attributes)?.IsRequired == true;

                var hasRequiredAttribute = requiredAttribute != null;
                if (hasRequiredAttribute || isDataContractMemberRequired || hasJsonNetAttributeRequired)
                {
                    parentSchema.RequiredProperties.Add(propertyName);
                }

                var isNullable = propertyTypeDescription.IsNullable &&
                                 hasRequiredAttribute == false &&
                                 isDataContractMemberRequired == false &&
                                 (property.Required == Required.Default || property.Required == Required.AllowNull);

                if (isNullable)
                {
                    if (Settings.NullHandling == NullHandling.JsonSchema)
                    {
                        if (requiresSchemaReference)
                        {
                            jsonProperty.OneOf.Add(new JsonSchema4 {
                                Type = JsonObjectType.Null
                            });
                        }
                        else if (jsonProperty.Type == JsonObjectType.None)
                        {
                            jsonProperty.OneOf.Add(new JsonSchema4 {
                                Type = JsonObjectType.None
                            });
                            jsonProperty.OneOf.Add(new JsonSchema4 {
                                Type = JsonObjectType.Null
                            });
                        }
                        else
                        {
                            jsonProperty.Type = jsonProperty.Type | JsonObjectType.Null;
                        }
                    }
                }
                else if (Settings.NullHandling == NullHandling.Swagger)
                {
                    if (!parentSchema.RequiredProperties.Contains(propertyName))
                    {
                        parentSchema.RequiredProperties.Add(propertyName);
                    }
                }

                dynamic readOnlyAttribute = attributes.TryGetIfAssignableTo("System.ComponentModel.ReadOnlyAttribute");
                if (readOnlyAttribute != null)
                {
                    jsonProperty.IsReadOnly = readOnlyAttribute.IsReadOnly;
                }

                jsonProperty.Description = await propertyInfo.GetDescriptionAsync(attributes).ConfigureAwait(false);

                ApplyPropertyAnnotations(jsonProperty, property, parentType, attributes, propertyTypeDescription);
            }
        }
Exemple #52
0
        private async Task LoadPropertyOrFieldAsync(Newtonsoft.Json.Serialization.JsonProperty property, MemberInfo propertyInfo, Type parentType, JsonSchema4 parentSchema, JsonSchemaResolver schemaResolver)
        {
            var propertyType            = property.PropertyType;
            var propertyAttributes      = property.AttributeProvider.GetAttributes(true).ToArray();
            var propertyTypeDescription = Settings.ReflectionService.GetDescription(propertyType, propertyAttributes, Settings);

            if (property.Ignored == false && IsPropertyIgnoredBySettings(propertyType, parentType, propertyAttributes) == false)
            {
                if (propertyType.Name == "Nullable`1")
#if !LEGACY
                { propertyType = propertyType.GenericTypeArguments[0]; }
#else
                { propertyType = propertyType.GetGenericArguments()[0]; }
#endif

                var propertyName = GetPropertyName(property, propertyInfo);
                if (parentSchema.Properties.ContainsKey(propertyName))
                {
                    throw new InvalidOperationException("The JSON property '" + propertyName + "' is defined multiple times on type '" + parentType.FullName + "'.");
                }

                var requiredAttribute = propertyAttributes.TryGetIfAssignableTo("System.ComponentModel.DataAnnotations.RequiredAttribute");

                var hasJsonNetAttributeRequired  = property.Required == Required.Always || property.Required == Required.AllowNull;
                var isDataContractMemberRequired = GetDataMemberAttribute(parentType, propertyAttributes)?.IsRequired == true;

                var hasRequiredAttribute = requiredAttribute != null;
                if (hasRequiredAttribute || isDataContractMemberRequired || hasJsonNetAttributeRequired)
                {
                    parentSchema.RequiredProperties.Add(propertyName);
                }

                var isNullable = propertyTypeDescription.IsNullable &&
                                 hasRequiredAttribute == false &&
                                 (bool)isDataContractMemberRequired == false &&
                                 (property.Required == Required.Default || property.Required == Required.AllowNull);

                var jsonProperty = await GenerateWithReferenceAndNullability <JsonProperty>(
                    propertyType, propertyAttributes, isNullable, schemaResolver, async (p, s) =>
                {
                    if (Settings.GenerateXmlObjects)
                    {
                        p.GenerateXmlObjectForProperty(parentType, propertyName, propertyAttributes);
                    }

                    if (Settings.SchemaType == SchemaType.JsonSchema &&
                        hasRequiredAttribute &&
                        requiredAttribute.TryGetPropertyValue("AllowEmptyStrings", false) == false)
                    {
                        p.MinLength = 1;
                    }

                    if (!isNullable && Settings.SchemaType == SchemaType.Swagger2)
                    {
                        if (!parentSchema.RequiredProperties.Contains(propertyName))
                        {
                            parentSchema.RequiredProperties.Add(propertyName);
                        }
                    }

                    dynamic readOnlyAttribute = propertyAttributes.TryGetIfAssignableTo("System.ComponentModel.ReadOnlyAttribute");
                    if (readOnlyAttribute != null)
                    {
                        p.IsReadOnly = readOnlyAttribute.IsReadOnly;
                    }

                    if (p.Description == null)
                    {
                        p.Description = await propertyInfo.GetDescriptionAsync(propertyAttributes).ConfigureAwait(false);
                    }

                    p.Default = ConvertDefaultValue(property);

                    ApplyDataAnnotations(p, propertyTypeDescription, propertyAttributes);
                }).ConfigureAwait(false);

                parentSchema.Properties.Add(propertyName, jsonProperty);
            }
        }
Exemple #53
0
        private void SerializeDictionary(JsonWriter writer, IWrappedDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContract collectionValueContract)
        {
            contract.InvokeOnSerializing(values.UnderlyingDictionary, Serializer.Context);

            SerializeStack.Add(values.UnderlyingDictionary);
            writer.WriteStartObject();

            bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);

            if (isReference)
            {
                writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
                writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values.UnderlyingDictionary));
            }
            if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract))
            {
                WriteTypeProperty(writer, values.UnderlyingDictionary.GetType());
            }

            JsonContract childValuesContract = Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));

            int initialDepth = writer.Top;

            // Mono Unity 3.0 fix
            IDictionary d = values;

            foreach (DictionaryEntry entry in d)
            {
                string propertyName = GetPropertyName(entry);

                propertyName = (contract.PropertyNameResolver != null)
                                                                 ? contract.PropertyNameResolver(propertyName)
                                                                 : propertyName;
                try
                {
                    object       value         = entry.Value;
                    JsonContract valueContract = GetContractSafe(value);

                    if (ShouldWriteReference(value, null, valueContract))
                    {
                        writer.WritePropertyName(propertyName);
                        WriteReference(writer, value);
                    }
                    else
                    {
                        if (!CheckForCircularReference(value, null, contract))
                        {
                            continue;
                        }

                        writer.WritePropertyName(propertyName);

                        SerializeValue(writer, value, valueContract, null, childValuesContract);
                    }
                }
                catch (Exception ex)
                {
                    if (IsErrorHandled(values.UnderlyingDictionary, contract, propertyName, ex))
                    {
                        HandleError(writer, initialDepth);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            writer.WriteEndObject();
            SerializeStack.RemoveAt(SerializeStack.Count - 1);

            contract.InvokeOnSerialized(values.UnderlyingDictionary, Serializer.Context);
        }
        private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
        {
            bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);

            // don't make readonly fields that aren't creator parameters the referenced value because they can't be deserialized to
            isReference = (isReference && (member == null || member.Writable || HasCreatorParameter(containerContract, member)));

            bool includeTypeDetails  = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty);
            bool writeMetadataObject = isReference || includeTypeDetails;

            if (writeMetadataObject)
            {
                writer.WriteStartObject();

                if (isReference)
                {
                    WriteReferenceIdProperty(writer, contract.UnderlyingType, values);
                }
                if (includeTypeDetails)
                {
                    WriteTypeProperty(writer, values.GetType());
                }
                writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false);
            }

            if (contract.ItemContract == null)
            {
                contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));
            }

            return(writeMetadataObject);
        }
Exemple #55
0
        private async Task GeneratePropertiesAndInheritanceAsync(Type type, JsonSchema4 schema, JsonSchemaResolver schemaResolver)
        {
#if !LEGACY
            var propertiesAndFields = type.GetTypeInfo()
                                      .DeclaredFields
                                      .Where(f => f.IsPublic && !f.IsStatic)
                                      .OfType <MemberInfo>()
                                      .Concat(
                type.GetTypeInfo().DeclaredProperties
                .Where(p => (p.GetMethod?.IsPublic == true && p.GetMethod?.IsStatic == false) ||
                       (p.SetMethod?.IsPublic == true && p.SetMethod?.IsStatic == false))
                )
                                      .ToList();
#else
            var propertiesAndFields = type.GetTypeInfo()
                                      .GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
                                      .Where(f => f.IsPublic && !f.IsStatic)
                                      .OfType <MemberInfo>()
                                      .Concat(
                type.GetTypeInfo()
                .GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
                .Where(p => (p.GetGetMethod()?.IsPublic == true && p.GetGetMethod()?.IsStatic == false) ||
                       (p.GetSetMethod()?.IsPublic == true && p.GetSetMethod()?.IsStatic == false))
                )
                                      .ToList();
#endif

            var contract = Settings.ResolveContract(type);

            var allowedProperties = GetTypeProperties(type);
            var objectContract    = contract as JsonObjectContract;
            if (objectContract != null && allowedProperties == null)
            {
                foreach (var property in objectContract.Properties.Where(p => p.DeclaringType == type))
                {
                    bool shouldSerialize;
                    try
                    {
                        shouldSerialize = property.ShouldSerialize?.Invoke(null) != false;
                    }
                    catch
                    {
                        shouldSerialize = true;
                    }

                    if (shouldSerialize)
                    {
                        var info         = propertiesAndFields.FirstOrDefault(p => p.Name == property.UnderlyingName);
                        var propertyInfo = info as PropertyInfo;
#if !LEGACY
                        if (Settings.GenerateAbstractProperties || propertyInfo == null ||
                            (propertyInfo.GetMethod?.IsAbstract != true && propertyInfo.SetMethod?.IsAbstract != true))
#else
                        if (Settings.GenerateAbstractProperties || propertyInfo == null ||
                            (propertyInfo.GetGetMethod()?.IsAbstract != true && propertyInfo.GetSetMethod()?.IsAbstract != true))
#endif
                        {
                            await LoadPropertyOrFieldAsync(property, info, type, schema, schemaResolver).ConfigureAwait(false);
                        }
                    }
                }
            }
            else
            {
                // TODO: Remove this hacky code (used to support serialization of exceptions and restore the old behavior [pre 9.x])
                foreach (var info in propertiesAndFields.Where(m => allowedProperties == null || allowedProperties.Contains(m.Name)))
                {
                    var attribute    = info.GetCustomAttributes(true).OfType <JsonPropertyAttribute>().SingleOrDefault();
                    var propertyType = (info as PropertyInfo)?.PropertyType ?? ((FieldInfo)info).FieldType;
                    var property     = new Newtonsoft.Json.Serialization.JsonProperty
                    {
                        AttributeProvider = new ReflectionAttributeProvider(info),
                        PropertyType      = propertyType,
                        Ignored           = IsPropertyIgnored(propertyType, type, info.GetCustomAttributes(true).OfType <Attribute>().ToArray())
                    };

                    if (attribute != null)
                    {
                        property.PropertyName         = attribute.PropertyName ?? info.Name;
                        property.Required             = attribute.Required;
                        property.DefaultValueHandling = attribute.DefaultValueHandling;
                        property.TypeNameHandling     = attribute.TypeNameHandling;
                        property.NullValueHandling    = attribute.NullValueHandling;
                        property.TypeNameHandling     = attribute.TypeNameHandling;
                    }
                    else
                    {
                        property.PropertyName = info.Name;
                    }

                    await LoadPropertyOrFieldAsync(property, info, type, schema, schemaResolver).ConfigureAwait(false);
                }
            }

            await GenerateInheritanceAsync(type, schema, schemaResolver).ConfigureAwait(false);
        }
        private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            JsonConverter converter =
                member?.Converter ??
                containerProperty?.ItemConverter ??
                containerContract?.ItemConverter ??
                valueContract.Converter ??
                Serializer.GetMatchingConverter(valueContract.UnderlyingType) ??
                valueContract.InternalConverter;

            if (converter != null && converter.CanWrite)
            {
                SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
                return;
            }

            switch (valueContract.ContractType)
            {
            case JsonContractType.Object:
                SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
                break;

            case JsonContractType.Array:
                JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
                if (!arrayContract.IsMultidimensionalArray)
                {
                    SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty);
                }
                else
                {
                    SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty);
                }
                break;

            case JsonContractType.Primitive:
                SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
                break;

            case JsonContractType.String:
                SerializeString(writer, value, (JsonStringContract)valueContract);
                break;

            case JsonContractType.Dictionary:
                JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
                SerializeDictionary(writer, (value is IDictionary dictionary) ? dictionary : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty);
                break;

#if HAVE_DYNAMIC
            case JsonContractType.Dynamic:
                SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty);
                break;
#endif
#if HAVE_BINARY_SERIALIZATION
            case JsonContractType.Serializable:
                SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty);
                break;
#endif
            case JsonContractType.Linq:
                ((JToken)value).WriteTo(writer, Serializer.Converters.ToArray());
                break;
            }
        }
        private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
        {
            if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
            {
                return(true);
            }

            ReferenceLoopHandling?referenceLoopHandling = null;

            if (property != null)
            {
                referenceLoopHandling = property.ReferenceLoopHandling;
            }

            if (referenceLoopHandling == null && containerProperty != null)
            {
                referenceLoopHandling = containerProperty.ItemReferenceLoopHandling;
            }

            if (referenceLoopHandling == null && containerContract != null)
            {
                referenceLoopHandling = containerContract.ItemReferenceLoopHandling;
            }

            bool exists = (Serializer._equalityComparer != null)
                ? _serializeStack.Contains(value, Serializer._equalityComparer)
                : _serializeStack.Contains(value);

            if (exists)
            {
                string message = "Self referencing loop detected";
                if (property != null)
                {
                    message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName);
                }
                message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType());

                switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling))
                {
                case ReferenceLoopHandling.Error:
                    throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);

                case ReferenceLoopHandling.Ignore:
                    if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
                    {
                        TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null);
                    }

                    return(false);

                case ReferenceLoopHandling.Serialize:
                    if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
                    {
                        TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null);
                    }

                    return(true);
                }
            }

            return(true);
        }
Exemple #58
0
        private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            OnSerializing(writer, contract, value);
            _serializeStack.Add(value);

            WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);

            int initialDepth = writer.Top;

            for (int index = 0; index < contract.Properties.Count; index++)
            {
                JsonProperty property = contract.Properties[index];

                // only write non-dynamic properties that have an explicit attribute
                if (property.HasMemberAttribute)
                {
                    try
                    {
                        if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue))
                        {
                            continue;
                        }

                        property.WritePropertyName(writer);
                        SerializeValue(writer, memberValue, memberContract, property, contract, member);
                    }
                    catch (Exception ex)
                    {
                        if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
                        {
                            HandleError(writer, initialDepth);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }

            foreach (string memberName in value.GetDynamicMemberNames())
            {
                if (contract.TryGetMember(value, memberName, out object memberValue))
                {
                    try
                    {
                        JsonContract valueContract = GetContractSafe(memberValue);

                        if (!ShouldWriteDynamicProperty(memberValue))
                        {
                            continue;
                        }

                        if (CheckForCircularReference(writer, memberValue, null, valueContract, contract, member))
                        {
                            string resolvedPropertyName = (contract.PropertyNameResolver != null)
                                ? contract.PropertyNameResolver(memberName)
                                : memberName;

                            writer.WritePropertyName(resolvedPropertyName);
                            SerializeValue(writer, memberValue, valueContract, null, contract, member);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (IsErrorHandled(value, contract, memberName, null, writer.ContainerPath, ex))
                        {
                            HandleError(writer, initialDepth);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }

            writer.WriteEndObject();

            _serializeStack.RemoveAt(_serializeStack.Count - 1);
            OnSerialized(writer, contract, value);
        }
        private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            if (value == null)
            {
                return(false);
            }
            if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String)
            {
                return(false);
            }

            bool?isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty);

            if (isReference == null)
            {
                if (valueContract.ContractType == JsonContractType.Array)
                {
                    isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
                }
                else
                {
                    isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
                }
            }

            if (!isReference.GetValueOrDefault())
            {
                return(false);
            }

            return(Serializer.GetReferenceResolver().IsReferenced(this, value));
        }
        private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices)
        {
            int dimension = indices.Length;

            int[] newIndices = new int[dimension + 1];
            for (int i = 0; i < dimension; i++)
            {
                newIndices[i] = indices[i];
            }

            writer.WriteStartArray();

            for (int i = values.GetLowerBound(dimension); i <= values.GetUpperBound(dimension); i++)
            {
                newIndices[dimension] = i;
                bool isTopLevel = (newIndices.Length == values.Rank);

                if (isTopLevel)
                {
                    object value = values.GetValue(newIndices);

                    try
                    {
                        JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);

                        if (ShouldWriteReference(value, null, valueContract, contract, member))
                        {
                            WriteReference(writer, value);
                        }
                        else
                        {
                            if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
                            {
                                SerializeValue(writer, value, valueContract, null, contract, member);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex))
                        {
                            HandleError(writer, initialDepth + 1);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
                else
                {
                    SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices);
                }
            }

            writer.WriteEndArray();
        }