Beispiel #1
0
        public void JsonConverter_CanConvert_Test()
        {
            var result = _jsonConverter.CanConvert(typeof(TaskQueueInfoDto));

            result.ShouldBeFalse();

            var result1 = _jsonConverter.CanConvert(typeof(Address));

            result1.ShouldBeTrue();
        }
        private static JsonConverter GetRuntimeProvidedCustomConverter(System.Type type, JsonSerializerOptions options)
        {
            System.Collections.Generic.IList <JsonConverter> converters = options.Converters;

            for (int i = 0; i < converters.Count; i++)
            {
                JsonConverter converter = converters[i];

                if (converter.CanConvert(type))
                {
                    if (converter is JsonConverterFactory factory)
                    {
                        converter = factory.CreateConverter(type, options);
                        if (converter == null || converter is JsonConverterFactory)
                        {
                            throw new System.InvalidOperationException($"The converter '{factory.GetType()}' cannot return null or a JsonConverterFactory instance.");
                        }
                    }

                    return(converter);
                }
            }

            return(null);
        }
Beispiel #3
0
        protected override JsonConverter ResolveContractConverter(Type objectType)
        {
            //if (ErrorConverter.CanConvertStatic(objectType))
            //    return new ErrorConverter();

            //if (ErrorListConverter.CanConvertStatic(objectType))
            //    return new ErrorListConverter();

            if (ResourceObjectConverter.CanConvert(objectType))
            {
                return(ResourceObjectConverter);
            }

            if (_resourceListConverter.CanConvert(objectType))
            {
                return(_resourceListConverter);
            }

            if (DocumentRootConverter.CanConvertStatic(objectType))
            {
                return(new DocumentRootConverter(_href));
            }

            return(base.ResolveContractConverter(objectType));
        }
Beispiel #4
0
        private static void GenericConverterTestHelper <T>(string converterName, object objectValue, string stringValue, JsonSerializerOptions options, bool nullOptionOkay = true)
        {
            JsonConverter <T> converter = (JsonConverter <T>)options.GetConverter(typeof(T));

            Assert.True(converter.CanConvert(typeof(T)));
            Assert.Equal(converterName, converter.GetType().Name);

            ReadOnlySpan <byte> data   = Encoding.UTF8.GetBytes(stringValue);
            Utf8JsonReader      reader = new Utf8JsonReader(data);

            reader.Read();

            T valueRead = converter.Read(ref reader, typeof(T), nullOptionOkay ? null: options);

            Assert.Equal(objectValue, valueRead);

            if (reader.TokenType != JsonTokenType.EndObject)
            {
                valueRead = converter.Read(ref reader, typeof(T), options);  // Test with given option if reader position haven't advanced.
                Assert.Equal(objectValue, valueRead);
            }

            using (var stream = new MemoryStream())
                using (var writer = new Utf8JsonWriter(stream))
                {
                    converter.Write(writer, (T)objectValue, options);
                    writer.Flush();
                    Assert.Equal(stringValue, Encoding.UTF8.GetString(stream.ToArray()));

                    writer.Reset(stream);
                    converter.Write(writer, (T)objectValue, nullOptionOkay ? null : options);
                    writer.Flush();
                    Assert.Equal(stringValue + stringValue, Encoding.UTF8.GetString(stream.ToArray()));
                }
        }
        protected override JsonConverter ResolveContractConverter(Type objectType)
        {
            if (ErrorConverter.CanConvertStatic(objectType))
            {
                return(new ErrorConverter());
            }

            if (ErrorListConverter.CanConvertStatic(objectType))
            {
                return(new ErrorListConverter());
            }

            if (ResourceObjectConverter.CanConvert(objectType))
            {
                return(ResourceObjectConverter);
            }

            if (_resourceObjectListConverter.CanConvert(objectType))
            {
                return(_resourceObjectListConverter);
            }

            if (LinkConverter.CanConvertStatic(objectType))
            {
                return(new LinkConverter());
            }

            if (DocumentRootConverter.CanConvertStatic(objectType))
            {
                return(new DocumentRootConverter());
            }

            return(base.ResolveContractConverter(objectType));
        }
Beispiel #6
0
        private JsonConverter GetRuntimeProvidedCustomConverter(Type type)
        {
            IList <JsonConverter> converters = Options.Converters;

            for (int i = 0; i < converters.Count; i++)
            {
                JsonConverter converter = converters[i];

                if (converter.CanConvert(type))
                {
                    if (converter is JsonConverterFactory factory)
                    {
                        converter = factory.CreateConverter(type, Options);
                        if (converter == null || converter is JsonConverterFactory)
                        {
                            throw new InvalidOperationException($"The converter '{factory.GetType()}' cannot return null or a JsonConverterFactory instance.");
                        }
                    }

                    return(converter);
                }
            }

            return(null);
        }
        public static JsonConverter GetJsonConverter(ICustomAttributeProvider attributeProvider, Type targetConvertedType)
        {
            object provider = null;

#if !NETFX_CORE
            provider = attributeProvider as MemberInfo;
#else
            provider = attributeProvider.UnderlyingObject;
#endif

            Type converterType = GetJsonConverterType(attributeProvider);

            if (converterType != null)
            {
                JsonConverter memberConverter = JsonConverterAttribute.CreateJsonConverterInstance(converterType);

                if (!memberConverter.CanConvert(targetConvertedType))
                {
                    throw new JsonSerializationException("JsonConverter {0} on {1} is not compatible with member type {2}.".FormatWith(CultureInfo.InvariantCulture, memberConverter.GetType().Name, provider, targetConvertedType.Name));
                }

                return(memberConverter);
            }

            return(null);
        }
 public override bool CanConvert(Type objectType)
 {
     if (MaskTypes.Contains(objectType))
     {
         return(false);
     }
     return(_Inner.CanConvert(objectType));
 }
Beispiel #9
0
        protected T ReadBson <T>(String bson, JsonConverter converter)
        {
            if (!converter.CanConvert(typeof(T)))
            {
                throw new InvalidOperationException();
            }

            using (var memoryStream = new MemoryStream(Convert.FromBase64String(RemovePreamble(bson)), writable: false))
                using (var bsonReader = new BsonReader(memoryStream))
                    return((T)converter.ReadJson(bsonReader, typeof(T), null, NewtonsoftBsonSerializer.Default.Serializer));
        }
Beispiel #10
0
        protected T ReadJson <T>(String json, JsonConverter converter)
        {
            if (!converter.CanConvert(typeof(T)))
            {
                throw new InvalidOperationException();
            }

            using (var stringReader = new StringReader(RemovePreamble(json)))
                using (var jsonReader = new JsonTextReader(stringReader))
                    return((T)converter.ReadJson(jsonReader, typeof(T), null, NewtonsoftBsonSerializer.Default.Serializer));
        }
        public override bool CanConvert(Type objectType)
        {
            if (objectType.IsGenericType && objectType.Name.Equals(typeof(List <>).Name))
            {
                var genericArgument = objectType.GetGenericArguments().FirstOrDefault();
                if (genericArgument != null)
                {
                    return(_elementConverter.CanConvert(genericArgument));
                }
            }

            return(false);
        }
Beispiel #12
0
        private static void TestOptionsConverter <T>(
            JsonConverter converter,
            T some,
            T none = default) where T : IOption <Boxed <int> >
        {
            Assert.True(converter.CanRead);
            Assert.True(converter.CanWrite);
            Assert.True(converter.CanConvert(some.GetType()));
            Assert.False(converter.CanConvert(typeof(int)));

            var settings = new JsonSerializerSettings
            {
                ContractResolver = new CustomContractResolver(converter, some.GetType())
            };

            var someStr = JsonConvert.SerializeObject(some, settings);

            Assert.AreEqual(some, JsonConvert.DeserializeObject <T>(someStr, settings));

            var strNone = JsonConvert.SerializeObject(none, settings);

            Assert.AreEqual(none, JsonConvert.DeserializeObject <T>(strNone, settings));
        }
Beispiel #13
0
        /// <inheritdoc />
        protected override JsonContract CreateContract(Type objectType)
        {
            JsonContract contract = base.CreateContract(objectType);

            if (DateTimeConverter.CanConvert(objectType))
            {
                contract.Converter = DateTimeConverter;
            }
            else if (ExplicitNullConverter.CanConvert(objectType))
            {
                contract.Converter = ExplicitNullConverter;
            }

            return(contract);
        }
Beispiel #14
0
        protected String WriteBson <T>(T value, JsonConverter converter)
        {
            if (!converter.CanConvert(typeof(T)))
            {
                throw new InvalidOperationException();
            }

            using (var memoryStream = new MemoryStream())
                using (var bsonWriter = new BsonWriter(memoryStream))
                {
                    converter.WriteJson(bsonWriter, value, NewtonsoftBsonSerializer.Default.Serializer);

                    return(Convert.ToBase64String(memoryStream.ToArray()));
                }
        }
        public static JsonConverter GetJsonConverter(ICustomAttributeProvider attributeProvider, Type targetConvertedType)
        {
            Type jsonConverterType = GetJsonConverterType(attributeProvider);

            if (jsonConverterType != null)
            {
                JsonConverter jsonConverter = JsonConverterAttribute.CreateJsonConverterInstance(jsonConverterType);
                if (!jsonConverter.CanConvert(targetConvertedType))
                {
                    throw new JsonSerializationException("JsonConverter {0} on {1} is not compatible with member type {2}.".FormatWith(CultureInfo.InvariantCulture, jsonConverter.GetType().Name, attributeProvider, targetConvertedType.Name));
                }
                return(jsonConverter);
            }
            return(null);
        }
Beispiel #16
0
        private void GenerateILForCallingConverter(Type valueType, Action pushValueOntoStack, JsonConverter converter)
        {
            if (!converter.CanConvert(valueType))
            {
                throw new InvalidOperationException("Converter is not compatible.");
            }

            Type converterType = converter.GetType();
            Type converterGenericTypeParameter = GetConverterGenericType(converterType);
            Type converterGenericType          = typeof(JsonConverter <>).MakeGenericType(new Type[] {
                converterGenericTypeParameter
            });

            // Save converter to a global variable
            FieldBuilder converterField;

            if (!_converterCache.TryGetValue(converter, out converterField))
            {
                string fieldName = @"Converter" + (++_converterCounter);
                converterField = _tb.DefineField(
                    fieldName: fieldName,
                    // Default converters are internal classes so here the abstract generic type must be used.
                    type: converterGenericType,
                    attributes: FieldAttributes.Public | FieldAttributes.Static
                    );

                _converterCache.Add(converter, converterField);

                _followUp += type =>
                {
                    FieldInfo field = type.GetField(fieldName);
                    field.SetValue(null, converter);
                };
            }

            // converter.Write(writer, obj.Property, _options);
            _ilg.Emit(OpCodes.Ldsfld, converterField);
            _ilg.Emit(OpCodes.Ldarg_1);
            pushValueOntoStack();
            _ilg.Emit(OpCodes.Ldsfld, _optionsField);
            _ilg.Emit(OpCodes.Callvirt, converterGenericType.GetMethod("Write", new Type[] {
                typeof(Utf8JsonWriter),
                converterGenericTypeParameter,
                typeof(JsonSerializerOptions)
            }));

            MarkNewJumpTableLabel();
        }
Beispiel #17
0
        public void CanConvert_IfObjectTypeIsInMapping_ReturnsTrue()
        {
            // Arrange
            Type typeInMapping = typeof(object);
            IDictionary <string, Type> typeMapping = new Dictionary <string, Type>
            {
                { "IgnoreTypeName", typeInMapping }
            };
            JsonConverter product = CreateProductUnderTest(typeMapping);

            // Act
            bool canConvert = product.CanConvert(typeInMapping);

            // Assert
            Assert.True(canConvert);
        }
Beispiel #18
0
        protected String WriteJson <T>(T value, JsonConverter converter)
        {
            if (!converter.CanConvert(typeof(T)))
            {
                throw new InvalidOperationException();
            }

            NewtonsoftJsonSerializer.Default.Serializer.Formatting = Formatting.Indented;

            var sb = new StringBuilder();

            using (var stringWriter = new StringWriter(sb))
                using (var jsonWriter = new JsonTextWriter(stringWriter))
                    converter.WriteJson(jsonWriter, value, NewtonsoftJsonSerializer.Default.Serializer);

            return(sb.ToString());
        }
        // Taken from Newtonsoft's Json.NET JsonSerializer
        internal static JsonConverter GetMatchingConverter(IList <JsonConverter> converters, Type objectType)
        {
            ValidationUtils.ArgumentNotNull(objectType, "objectType");

            if (converters != null)
            {
                for (int i = 0; i < converters.Count; i++)
                {
                    JsonConverter converter = converters[i];

                    if (converter.CanConvert(objectType))
                    {
                        return(converter);
                    }
                }
            }

            return(null);
        }
Beispiel #20
0
        // Taken from Newtonsoft's Json.NET JsonSerializer
        internal static JsonConverter GetMatchingConverter(IList <JsonConverter> converters, Type objectType)
        {
            if (objectType == null)
            {
                throw new ArgumentNullException("objectType");
            }

            if (converters != null)
            {
                for (int i = 0; i < converters.Count; i++)
                {
                    JsonConverter converter = converters[i];

                    if (converter.CanConvert(objectType))
                    {
                        return(converter);
                    }
                }
            }

            return(null);
        }
Beispiel #21
0
 /// <inheritdoc />
 public override bool CanConvert(Type objectType) => _instantTimeConverter.CanConvert(objectType) ||
 _logicalTimeConverter.CanConvert(objectType);
Beispiel #22
0
 /// <summary>
 /// Indicates if the <see cref="NullHandlingConverter"/> can be used with
 /// a given type.
 /// </summary>
 /// <param name="objectType">
 /// The type under consideration.
 /// </param>
 /// <returns>
 /// <c>true</c> for value types and <c>false</c> otherwise.
 /// </returns>
 public override bool CanConvert(Type objectType)
 {
     return(objectType.GetTypeInfo().IsValueType || (inner != null && inner.CanConvert(objectType)));
 }
 public override bool CanConvert(Type typeToConvert)
 {
     return(original.CanConvert(typeToConvert));
 }
Beispiel #24
0
 public override bool CanConvert(Type objectType)
 {
     return(_inner.CanConvert(objectType) || objectType == typeof(PropertyExceptionDescriptor));
 }
Beispiel #25
0
 public override bool CanConvert(Type objectType) => original.CanConvert(objectType);
Beispiel #26
0
 public override bool CanConvert(Type objectType)
 => _converter.CanConvert(objectType);
 public override bool CanConvert(Type objectType)
 {
     return(converter.CanConvert(objectType));
 }
 public static void AssertCanConvert(JsonConverter subject, object o)
 {
     subject.CanConvert(o.GetType()).Should().BeTrue();
 }
        public override bool CanConvert(Type objectType)
        {
            Type elementType;

            return(ListUtil.IsList(objectType, out elementType) && ResourceObjectConverter.CanConvert(elementType));
        }
Beispiel #30
0
 public static bool CanConvertStatic(Type objectType, JsonConverter elementConvertor)
 {
     return(ListUtil.IsList(objectType, out Type elementType) &&
            elementConvertor.CanConvert(elementType));
 }