public MainPage() { InitializeComponent(); isoSettings = IsolatedStorageSettings.ApplicationSettings; basicJsonObjectConverter = new JsonConverter<BasicJsonObject>(); // TODO Remove App.Settings.APP_ID = "cylinder-manager-e30"; App.Settings.API_KEY = "d6c6b4b7aa0f4162a04f23ebd34c6d2e"; App.Settings.ADMIN_KEY = "e4b4709e31924777a4521df5fbf57692"; data = new BasicJsonObject(); // use two-way binding to set BasicjsonObject's key/value pairs JsonObjectGrid.DataContext = data; if (isoSettings.Contains(SETTINGS_BUCKET_NAME)) BucketName_Box.Text = isoSettings[SETTINGS_BUCKET_NAME] as string; if (isoSettings.Contains(SETTINGS_OBJECT_ID)) ObjectId_Box.Text = isoSettings[SETTINGS_OBJECT_ID] as string; if (isoSettings.Contains(SETTINGS_CCID)) CCID_Box.Text = isoSettings[SETTINGS_CCID] as string; if (isoSettings.Contains(SETTINGS_CLIENT_ID)) ClientId_Box.Text = isoSettings[SETTINGS_CLIENT_ID] as string; }
public void TryConvertingFromStreamEmptyToSimpleObject() { using (Stream stream = examples.EmptyObject()) { JsonConverter<ObjectWithName> converter = new JsonConverter<ObjectWithName>(); ObjectWithName objectExpected = converter.ConvertFrom(stream); } }
public void TryConvertingFromJsonToSimpleObject() { using (Stream stream = examples.JsonStream()) { JsonConverter<ObjectWithName> converter = new JsonConverter<ObjectWithName>(); ObjectWithName objectPopulated = converter.ConvertFrom(stream); Assert.IsTrue(objectPopulated.Name == Constants.MockObjectValue); } }
public void TryConvertingFromEmptyValidObjectToSimpleObject() { using (Stream stream = examples.EmptyValidObject()) { JsonConverter<ObjectWithName> converter = new JsonConverter<ObjectWithName>(); ObjectWithName objectExpected = converter.ConvertFrom(stream); Assert.IsTrue(objectExpected.Name == new ObjectWithName().Name); } }
private void SerializeValue(JsonWriter writer, object value, JsonConverter memberConverter) { JsonConverter converter = memberConverter; if (value == null) { writer.WriteNull(); } else if (converter != null || _serializer.HasClassConverter(value.GetType(), out converter) || _serializer.HasMatchingConverter(value.GetType(), out converter)) { SerializeConvertable(writer, converter, value); } else if (JsonConvert.IsJsonPrimitive(value)) { writer.WriteValue(value); } else if (value is JToken) { ((JToken)value).WriteTo(writer, (_serializer.Converters != null) ? _serializer.Converters.ToArray() : null); } else if (value is JsonRaw) { writer.WriteRawValue(((JsonRaw)value).Content); } else { JsonContract contract = _serializer.ContractResolver.ResolveContract(value.GetType()); if (contract is JsonObjectContract) { SerializeObject(writer, value, (JsonObjectContract)contract); } else if (contract is JsonDictionaryContract) { SerializeDictionary(writer, (IDictionary)value, (JsonDictionaryContract)contract); } else if (contract is JsonArrayContract) { if (value is IList) { SerializeList(writer, (IList)value, (JsonArrayContract)contract); } else if (value is IEnumerable) { SerializeEnumerable(writer, (IEnumerable)value, (JsonArrayContract)contract); } else { throw new Exception("Cannot serialize '{0}' into a JSON array. Type does not implement IEnumerable.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); } } } }
public JsonMemberMapping(string mappingName, MemberInfo member, bool ignored, bool readable, bool writable, JsonConverter memberConverter, object defaultValue, bool required) { _mappingName = mappingName; _member = member; _ignored = ignored; _readable = readable; _writable = writable; _memberConverter = memberConverter; _defaultValue = defaultValue; _required = required; }
// Token: 0x06000BC9 RID: 3017 // RVA: 0x00044940 File Offset: 0x00042B40 private bool CalculatePropertyDetails(JsonProperty property, ref JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target, out bool useExistingValue, out object currentValue, out JsonContract propertyContract, out bool gottenCurrentValue) { currentValue = null; useExistingValue = false; propertyContract = null; gottenCurrentValue = false; if (property.Ignored) { return true; } JsonToken tokenType = reader.TokenType; if (property.PropertyContract == null) { property.PropertyContract = this.GetContractSafe(property.PropertyType); } ObjectCreationHandling valueOrDefault = property.ObjectCreationHandling.GetValueOrDefault(this.Serializer._objectCreationHandling); if (valueOrDefault != ObjectCreationHandling.Replace && (tokenType == JsonToken.StartArray || tokenType == JsonToken.StartObject) && property.Readable) { currentValue = property.ValueProvider.GetValue(target); gottenCurrentValue = true; if (currentValue != null) { propertyContract = this.GetContractSafe(currentValue.GetType()); useExistingValue = (!propertyContract.IsReadOnlyOrFixedSize && !TypeExtensions.IsValueType(propertyContract.UnderlyingType)); } } if (!property.Writable && !useExistingValue) { return true; } if (property.NullValueHandling.GetValueOrDefault(this.Serializer._nullValueHandling) == NullValueHandling.Ignore && tokenType == JsonToken.Null) { return true; } if (this.HasFlag(property.DefaultValueHandling.GetValueOrDefault(this.Serializer._defaultValueHandling), DefaultValueHandling.Ignore) && !this.HasFlag(property.DefaultValueHandling.GetValueOrDefault(this.Serializer._defaultValueHandling), DefaultValueHandling.Populate) && JsonTokenUtils.IsPrimitiveToken(tokenType) && MiscellaneousUtils.ValueEquals(reader.Value, property.GetResolvedDefaultValue())) { return true; } if (currentValue == null) { propertyContract = property.PropertyContract; } else { propertyContract = this.GetContractSafe(currentValue.GetType()); if (propertyContract != property.PropertyContract) { propertyConverter = this.GetConverter(propertyContract, property.MemberConverter, containerContract, containerProperty); } } return false; }
// Token: 0x06000BBE RID: 3006 // RVA: 0x00043B38 File Offset: 0x00041D38 private JsonConverter GetConverter(JsonContract contract, JsonConverter memberConverter, JsonContainerContract containerContract, JsonProperty containerProperty) { JsonConverter result = null; if (memberConverter != null) { result = memberConverter; } else if (containerProperty != null && containerProperty.ItemConverter != null) { result = containerProperty.ItemConverter; } else if (containerContract != null && containerContract.ItemConverter != null) { result = containerContract.ItemConverter; } else if (contract != null) { JsonConverter matchingConverter; if (contract.Converter != null) { result = contract.Converter; } else if ((matchingConverter = this.Serializer.GetMatchingConverter(contract.UnderlyingType)) != null) { result = matchingConverter; } else if (contract.InternalConverter != null) { result = contract.InternalConverter; } } return result; }
internal override void Initialize( Type parentClassType, Type declaredPropertyType, ConverterStrategy converterStrategy, MemberInfo?memberInfo, bool isVirtual, JsonConverter converter, JsonIgnoreCondition?ignoreCondition, JsonNumberHandling?parentTypeNumberHandling, JsonSerializerOptions options) { base.Initialize( parentClassType, declaredPropertyType, converterStrategy, memberInfo, isVirtual, converter, ignoreCondition, parentTypeNumberHandling, options); switch (memberInfo) { case PropertyInfo propertyInfo: { bool useNonPublicAccessors = GetAttribute <JsonIncludeAttribute>(propertyInfo) != null; MethodInfo?getMethod = propertyInfo.GetMethod; if (getMethod != null && (getMethod.IsPublic || useNonPublicAccessors)) { HasGetter = true; Get = options.MemberAccessorStrategy.CreatePropertyGetter <T>(propertyInfo); } MethodInfo?setMethod = propertyInfo.SetMethod; if (setMethod != null && (setMethod.IsPublic || useNonPublicAccessors)) { HasSetter = true; Set = options.MemberAccessorStrategy.CreatePropertySetter <T>(propertyInfo); } MemberType = MemberTypes.Property; break; } case FieldInfo fieldInfo: { Debug.Assert(fieldInfo.IsPublic); HasGetter = true; Get = options.MemberAccessorStrategy.CreateFieldGetter <T>(fieldInfo); if (!fieldInfo.IsInitOnly) { HasSetter = true; Set = options.MemberAccessorStrategy.CreateFieldSetter <T>(fieldInfo); } MemberType = MemberTypes.Field; break; } default: { IsForTypeInfo = true; HasGetter = true; HasSetter = true; break; } } _converterIsExternalAndPolymorphic = !converter.IsInternalConverter && PropertyType != converter.TypeToConvert; PropertyTypeCanBeNull = PropertyType.CanBeNull(); _propertyTypeEqualsTypeToConvert = typeof(T) == PropertyType; GetPolicies(ignoreCondition, parentTypeNumberHandling); }
/// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/>s which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { if (converters != null && converters.Length > 0 && _value != null) { JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); if (matchingConverter != null && matchingConverter.CanWrite) { matchingConverter.WriteJson(writer, _value, JsonSerializer.CreateDefault()); return; } } switch (_valueType) { case JTokenType.Comment: writer.WriteComment(_value?.ToString()); return; case JTokenType.Raw: writer.WriteRawValue(_value?.ToString()); return; case JTokenType.Null: writer.WriteNull(); return; case JTokenType.Undefined: writer.WriteUndefined(); return; case JTokenType.Integer: if (_value is int) { writer.WriteValue((int)_value); } else if (_value is long) { writer.WriteValue((long)_value); } else if (_value is ulong) { writer.WriteValue((ulong)_value); } #if HAVE_BIG_INTEGER else if (_value is BigInteger) { writer.WriteValue((BigInteger)_value); } #endif else { writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture)); } return; case JTokenType.Float: if (_value is decimal) { writer.WriteValue((decimal)_value); } else if (_value is double) { writer.WriteValue((double)_value); } else if (_value is float) { writer.WriteValue((float)_value); } else { writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture)); } return; case JTokenType.String: writer.WriteValue(_value?.ToString()); return; case JTokenType.Boolean: writer.WriteValue(Convert.ToBoolean(_value, CultureInfo.InvariantCulture)); return; case JTokenType.Date: #if HAVE_DATE_TIME_OFFSET if (_value is DateTimeOffset) { writer.WriteValue((DateTimeOffset)_value); } else #endif { writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture)); } return; case JTokenType.Bytes: writer.WriteValue((byte[])_value); return; case JTokenType.Guid: writer.WriteValue((_value != null) ? (Guid?)_value : null); return; case JTokenType.TimeSpan: writer.WriteValue((_value != null) ? (TimeSpan?)_value : null); return; case JTokenType.Uri: writer.WriteValue((Uri)_value); return; } throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(Type), _valueType, "Unexpected token type."); }
private static bool WriteCore <TValue>( JsonConverter jsonConverter, Utf8JsonWriter writer, in TValue value,
public JsonTypeConverterWrapper(JsonTypeConverter typeConverter, JsonConverter jsonConverter) { this.typeConverter = typeConverter; this.jsonConverter = jsonConverter; }
private object CreateValue(JsonReader reader, Type objectType, object existingValue, JsonConverter memberConverter) { JsonConverter converter; if (memberConverter != null) return memberConverter.ReadJson(reader, objectType, GetInternalSerializer()); if (objectType != null && _serializer.HasClassConverter(objectType, out converter)) return converter.ReadJson(reader, objectType, GetInternalSerializer()); if (objectType != null && _serializer.HasMatchingConverter(objectType, out converter)) return converter.ReadJson(reader, objectType, GetInternalSerializer()); if (objectType == typeof (JsonRaw)) return JsonRaw.Create(reader); do { switch (reader.TokenType) { // populate a typed object or generic dictionary/array // depending upon whether an objectType was supplied case JsonToken.StartObject: return CreateObject(reader, objectType, existingValue); case JsonToken.StartArray: return CreateList(reader, objectType, existingValue, null); case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Date: return EnsureType(reader.Value, objectType); case JsonToken.StartConstructor: case JsonToken.EndConstructor: string constructorName = reader.Value.ToString(); return constructorName; case JsonToken.Null: case JsonToken.Undefined: if (objectType == typeof (DBNull)) return DBNull.Value; return null; case JsonToken.Comment: // ignore break; default: throw new JsonSerializationException("Unexpected token while deserializing object: " + reader.TokenType); } } while (reader.Read()); throw new JsonSerializationException("Unexpected end when deserializing object."); }
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { Type converterType; Type[] genericArgs; Type? elementType = null; Type? dictionaryKeyType = null; Type? actualTypeToConvert; // Array if (typeToConvert.IsArray) { // Verify that we don't have a multidimensional array. if (typeToConvert.GetArrayRank() > 1) { ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(typeToConvert); } converterType = typeof(ArrayConverter <,>); elementType = typeToConvert.GetElementType(); } // List<> or deriving from List<> else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericBaseClass(typeof(List <>))) != null) { converterType = typeof(ListOfTConverter <,>); elementType = actualTypeToConvert.GetGenericArguments()[0]; } // Dictionary<TKey, TValue> or deriving from Dictionary<TKey, TValue> else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericBaseClass(typeof(Dictionary <,>))) != null) { genericArgs = actualTypeToConvert.GetGenericArguments(); converterType = typeof(DictionaryOfTKeyTValueConverter <, ,>); dictionaryKeyType = genericArgs[0]; elementType = genericArgs[1]; } // Immutable dictionaries from System.Collections.Immutable, e.g. ImmutableDictionary<TKey, TValue> else if (typeToConvert.IsImmutableDictionaryType()) { genericArgs = typeToConvert.GetGenericArguments(); converterType = typeof(ImmutableDictionaryOfTKeyTValueConverter <, ,>); dictionaryKeyType = genericArgs[0]; elementType = genericArgs[1]; } // IDictionary<TKey, TValue> or deriving from IDictionary<TKey, TValue> else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericInterface(typeof(IDictionary <,>))) != null) { genericArgs = actualTypeToConvert.GetGenericArguments(); converterType = typeof(IDictionaryOfTKeyTValueConverter <, ,>); dictionaryKeyType = genericArgs[0]; elementType = genericArgs[1]; } // IReadOnlyDictionary<TKey, TValue> or deriving from IReadOnlyDictionary<TKey, TValue> else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericInterface(typeof(IReadOnlyDictionary <,>))) != null) { genericArgs = actualTypeToConvert.GetGenericArguments(); converterType = typeof(IReadOnlyDictionaryOfTKeyTValueConverter <, ,>); dictionaryKeyType = genericArgs[0]; elementType = genericArgs[1]; } // Immutable non-dictionaries from System.Collections.Immutable, e.g. ImmutableStack<T> else if (typeToConvert.IsImmutableEnumerableType()) { converterType = typeof(ImmutableEnumerableOfTConverter <,>); elementType = typeToConvert.GetGenericArguments()[0]; } // IList<> else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericInterface(typeof(IList <>))) != null) { converterType = typeof(IListOfTConverter <,>); elementType = actualTypeToConvert.GetGenericArguments()[0]; } // ISet<> else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericInterface(typeof(ISet <>))) != null) { converterType = typeof(ISetOfTConverter <,>); elementType = actualTypeToConvert.GetGenericArguments()[0]; } // ICollection<> else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericInterface(typeof(ICollection <>))) != null) { converterType = typeof(ICollectionOfTConverter <,>); elementType = actualTypeToConvert.GetGenericArguments()[0]; } // Stack<> or deriving from Stack<> else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericBaseClass(typeof(Stack <>))) != null) { converterType = typeof(StackOfTConverter <,>); elementType = actualTypeToConvert.GetGenericArguments()[0]; } // Queue<> or deriving from Queue<> else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericBaseClass(typeof(Queue <>))) != null) { converterType = typeof(QueueOfTConverter <,>); elementType = actualTypeToConvert.GetGenericArguments()[0]; } // ConcurrentStack<> or deriving from ConcurrentStack<> else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericBaseClass(typeof(ConcurrentStack <>))) != null) { converterType = typeof(ConcurrentStackOfTConverter <,>); elementType = actualTypeToConvert.GetGenericArguments()[0]; } // ConcurrentQueue<> or deriving from ConcurrentQueue<> else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericBaseClass(typeof(ConcurrentQueue <>))) != null) { converterType = typeof(ConcurrentQueueOfTConverter <,>); elementType = actualTypeToConvert.GetGenericArguments()[0]; } // IEnumerable<>, types assignable from List<> else if ((actualTypeToConvert = typeToConvert.GetCompatibleGenericInterface(typeof(IEnumerable <>))) != null) { converterType = typeof(IEnumerableOfTConverter <,>); elementType = actualTypeToConvert.GetGenericArguments()[0]; } // Check for non-generics after checking for generics. else if (typeof(IDictionary).IsAssignableFrom(typeToConvert)) { if (typeToConvert == typeof(IDictionary)) { return(s_converterForIDictionary); } converterType = typeof(IDictionaryConverter <>); } else if (typeof(IList).IsAssignableFrom(typeToConvert)) { if (typeToConvert == typeof(IList)) { return(s_converterForIList); } converterType = typeof(IListConverter <>); } else if (typeToConvert.IsNonGenericStackOrQueue()) { converterType = typeof(IEnumerableWithAddMethodConverter <>); } else { Debug.Assert(typeof(IEnumerable).IsAssignableFrom(typeToConvert)); if (typeToConvert == typeof(IEnumerable)) { return(s_converterForIEnumerable); } converterType = typeof(IEnumerableConverter <>); } Type genericType; int numberOfGenericArgs = converterType.GetGenericArguments().Length; if (numberOfGenericArgs == 1) { genericType = converterType.MakeGenericType(typeToConvert); } else if (numberOfGenericArgs == 2) { genericType = converterType.MakeGenericType(typeToConvert, elementType !); } else { Debug.Assert(numberOfGenericArgs == 3); genericType = converterType.MakeGenericType(typeToConvert, dictionaryKeyType !, elementType !); } JsonConverter converter = (JsonConverter)Activator.CreateInstance( genericType, BindingFlags.Instance | BindingFlags.Public, binder: null, args: null, culture: null) !; return(converter); }
/// <summary> /// Returns true if successful, false is the reader ran out of buffer. /// Sets state.Current.ReturnValue to the reference target for $ref cases; /// Sets state.Current.ReturnValue to a new instance for $id cases. /// </summary> internal static bool ResolveMetadataForJsonObject <T>( ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { JsonConverter converter = state.Current.JsonTypeInfo.PropertyInfoForTypeInfo.ConverterBase; if (state.Current.ObjectState < StackFrameObjectState.ReadAheadNameOrEndObject) { // Read the first metadata property name. if (!TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadNameOrEndObject)) { return(false); } } if (state.Current.ObjectState == StackFrameObjectState.ReadNameOrEndObject) { if (reader.TokenType != JsonTokenType.PropertyName) { // Since this was an empty object, we are done reading metadata. state.Current.ObjectState = StackFrameObjectState.PropertyValue; // Skip the read of the first property name, since we already read it above. state.Current.PropertyState = StackFramePropertyState.ReadName; return(true); } ReadOnlySpan <byte> propertyName = reader.GetSpan(); MetadataPropertyName metadata = GetMetadataPropertyName(propertyName); if (metadata == MetadataPropertyName.Id) { state.Current.JsonPropertyName = s_idPropertyName; if (!converter.CanHaveIdMetadata) { ThrowHelper.ThrowJsonException_MetadataCannotParsePreservedObjectIntoImmutable(converter.TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.ReadAheadIdValue; } else if (metadata == MetadataPropertyName.Ref) { state.Current.JsonPropertyName = s_refPropertyName; if (converter.IsValueType) { ThrowHelper.ThrowJsonException_MetadataInvalidReferenceToValueType(converter.TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.ReadAheadRefValue; } else if (metadata == MetadataPropertyName.Values) { ThrowHelper.ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(propertyName, ref state, reader); } else { Debug.Assert(metadata == MetadataPropertyName.NoMetadata); // We are done reading metadata, the object didn't contain any. state.Current.ObjectState = StackFrameObjectState.PropertyValue; // Skip the read of the first property name, since we already read it above. state.Current.PropertyState = StackFramePropertyState.ReadName; return(true); } } if (state.Current.ObjectState == StackFrameObjectState.ReadAheadRefValue) { if (!TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadRefValue)) { return(false); } } else if (state.Current.ObjectState == StackFrameObjectState.ReadAheadIdValue) { if (!TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadIdValue)) { return(false); } } if (state.Current.ObjectState == StackFrameObjectState.ReadRefValue) { if (reader.TokenType != JsonTokenType.String) { ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType); } string referenceId = reader.GetString() !; object value = state.ReferenceResolver.ResolveReference(referenceId); ValidateValueIsCorrectType <T>(value, referenceId); state.Current.ReturnValue = value; state.Current.ObjectState = StackFrameObjectState.ReadAheadRefEndObject; } else if (state.Current.ObjectState == StackFrameObjectState.ReadIdValue) { if (reader.TokenType != JsonTokenType.String) { ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType); } converter.CreateInstanceForReferenceResolver(ref reader, ref state, options); string referenceId = reader.GetString() !; state.ReferenceResolver.AddReference(referenceId, state.Current.ReturnValue !); // We are done reading metadata plus we instantiated the object. state.Current.ObjectState = StackFrameObjectState.CreatedObject; } // Clear the metadata property name that was set in case of failure on ResolveReference/AddReference. state.Current.JsonPropertyName = null; if (state.Current.ObjectState == StackFrameObjectState.ReadAheadRefEndObject) { if (!TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadRefEndObject)) { return(false); } } if (state.Current.ObjectState == StackFrameObjectState.ReadRefEndObject) { if (reader.TokenType != JsonTokenType.EndObject) { // We just read a property. The only valid next tokens are EndObject and PropertyName. Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(reader.GetSpan(), ref state); } } return(true); }
/// <summary> /// Returns true if successful, false is the reader ran out of buffer. /// Sets state.Current.ReturnValue to the reference target for $ref cases; /// Sets state.Current.ReturnValue to a new instance for $id cases. /// </summary> internal static bool ResolveMetadataForJsonArray <T>( ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { JsonConverter converter = state.Current.JsonTypeInfo.PropertyInfoForTypeInfo.ConverterBase; if (state.Current.ObjectState < StackFrameObjectState.ReadAheadNameOrEndObject) { // Read the first metadata property name. if (!TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadNameOrEndObject)) { return(false); } } if (state.Current.ObjectState == StackFrameObjectState.ReadNameOrEndObject) { if (reader.TokenType != JsonTokenType.PropertyName) { // The reader should have detected other invalid cases. Debug.Assert(reader.TokenType == JsonTokenType.EndObject); // An enumerable needs metadata since it starts with StartObject. ThrowHelper.ThrowJsonException_MetadataPreservedArrayValuesNotFound(ref state, converter.TypeToConvert); } ReadOnlySpan <byte> propertyName = reader.GetSpan(); MetadataPropertyName metadata = GetMetadataPropertyName(propertyName); if (metadata == MetadataPropertyName.Id) { state.Current.JsonPropertyName = s_idPropertyName; if (!converter.CanHaveIdMetadata) { ThrowHelper.ThrowJsonException_MetadataCannotParsePreservedObjectIntoImmutable(converter.TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.ReadAheadIdValue; } else if (metadata == MetadataPropertyName.Ref) { state.Current.JsonPropertyName = s_refPropertyName; if (converter.IsValueType) { ThrowHelper.ThrowJsonException_MetadataInvalidReferenceToValueType(converter.TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.ReadAheadRefValue; } else if (metadata == MetadataPropertyName.Values) { ThrowHelper.ThrowJsonException_MetadataMissingIdBeforeValues(ref state, propertyName); } else { Debug.Assert(metadata == MetadataPropertyName.NoMetadata); // Having a StartObject without metadata properties is not allowed. ThrowHelper.ThrowJsonException_MetadataPreservedArrayInvalidProperty(ref state, converter.TypeToConvert, reader); } } if (state.Current.ObjectState == StackFrameObjectState.ReadAheadRefValue) { if (!TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadRefValue)) { return(false); } } else if (state.Current.ObjectState == StackFrameObjectState.ReadAheadIdValue) { if (!TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadIdValue)) { return(false); } } if (state.Current.ObjectState == StackFrameObjectState.ReadRefValue) { if (reader.TokenType != JsonTokenType.String) { ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType); } string referenceId = reader.GetString() !; object value = state.ReferenceResolver.ResolveReference(referenceId); ValidateValueIsCorrectType <T>(value, referenceId); state.Current.ReturnValue = value; state.Current.ObjectState = StackFrameObjectState.ReadAheadRefEndObject; } else if (state.Current.ObjectState == StackFrameObjectState.ReadIdValue) { if (reader.TokenType != JsonTokenType.String) { ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType); } converter.CreateInstanceForReferenceResolver(ref reader, ref state, options); string referenceId = reader.GetString() !; state.ReferenceResolver.AddReference(referenceId, state.Current.ReturnValue !); // Need to Read $values property name. state.Current.ObjectState = StackFrameObjectState.ReadAheadValuesName; } // Clear the metadata property name that was set in case of failure on ResolverReference/AddReference. state.Current.JsonPropertyName = null; if (state.Current.ObjectState == StackFrameObjectState.ReadAheadRefEndObject) { if (!TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadRefEndObject)) { return(false); } } if (state.Current.ObjectState == StackFrameObjectState.ReadRefEndObject) { if (reader.TokenType != JsonTokenType.EndObject) { // We just read a property. The only valid next tokens are EndObject and PropertyName. Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(reader.GetSpan(), ref state); } return(true); } if (state.Current.ObjectState == StackFrameObjectState.ReadAheadValuesName) { if (!TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadValuesName)) { return(false); } } if (state.Current.ObjectState == StackFrameObjectState.ReadValuesName) { if (reader.TokenType != JsonTokenType.PropertyName) { ThrowHelper.ThrowJsonException_MetadataPreservedArrayValuesNotFound(ref state, converter.TypeToConvert); } ReadOnlySpan <byte> propertyName = reader.GetSpan(); if (GetMetadataPropertyName(propertyName) != MetadataPropertyName.Values) { ThrowHelper.ThrowJsonException_MetadataPreservedArrayInvalidProperty(ref state, converter.TypeToConvert, reader); } // Remember the property in case we get an exception in one of the array elements. state.Current.JsonPropertyName = s_valuesPropertyName; state.Current.ObjectState = StackFrameObjectState.ReadAheadValuesStartArray; } if (state.Current.ObjectState == StackFrameObjectState.ReadAheadValuesStartArray) { if (!TryReadAheadMetadataAndSetState(ref reader, ref state, StackFrameObjectState.ReadValuesStartArray)) { return(false); } } if (state.Current.ObjectState == StackFrameObjectState.ReadValuesStartArray) { // Temporary workaround for the state machine accidentally // erasing the JsonPropertyName property in certain async // re-entrancy patterns. state.Current.JsonPropertyName = s_valuesPropertyName; if (reader.TokenType != JsonTokenType.StartArray) { ThrowHelper.ThrowJsonException_MetadataValuesInvalidToken(reader.TokenType); } state.Current.ValidateEndTokenOnArray = true; state.Current.ObjectState = StackFrameObjectState.CreatedObject; } return(true); }
/// <summary> /// Executes the request. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="apiRequest">The API request.</param> /// <param name="converter">The converter.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="customHeaders">Custom headers sending with request.</param> /// <returns></returns> /// <exception cref="DataServiceException"></exception> public async Task <Response <Tuple <T, Dictionary <string, string> > > > ExecuteRequestWithResponseAsync <T>( ApiRequest apiRequest, JsonConverter converter, Dictionary <string, string> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (cancellationToken.IsCancellationRequested) { return(new Response <Tuple <T, Dictionary <string, string> > >()); } try { var handler = new HttpClientHandler(); if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | (SecurityProtocolType)768 | (SecurityProtocolType)3072; var request = new HttpRequestMessage(apiRequest.Method, $"{apiRequest.BaseUri}{apiRequest.BuildParametersString() ?? string.Empty}"); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (!string.IsNullOrEmpty(apiRequest.AuthHeaderValue)) { request.Headers.Add("Authorization", apiRequest.AuthHeaderValue); } if (customHeaders != null) { foreach (var customHeader in customHeaders) { request.Headers.Add(customHeader.Key, customHeader.Value); } } if (!string.IsNullOrEmpty(apiRequest.Body)) { request.Content = new StringContent(apiRequest.Body); } var client = new HttpClient(handler); var response = await client.SendAsync(request, cancellationToken); if (response != null) { var responseBytes = await response.Content.ReadAsByteArrayAsync(); var responseContent = Encoding.UTF8.GetString(responseBytes, 0, responseBytes.Length); var apiError = await GetErrorResult(response); if (apiError != null) { throw new DataServiceException(apiError); } var result = DeserializeJson <T>(responseContent, apiRequest.Path, converter); Dictionary <string, string> headers = null; if (response.Headers != null) { var responseHeaders = response.Headers.ToArray(); headers = responseHeaders.ToDictionary(h => h.Key, v => string.Join(";", v.Value)); } return(new Response <Tuple <T, Dictionary <string, string> > > { Data = new Tuple <T, Dictionary <string, string> >(result, headers), RawBytes = responseBytes }); } else { throw new DataServiceException(new ApiError()); } } catch (OperationCanceledException) { return(new Response <Tuple <T, Dictionary <string, string> > >()); } catch (HttpRequestException ex) { throw new DataServiceException(GetErrorResult(ex)); } catch (Exception ex) { if (ex is DataServiceException) { throw; } else { throw new DataServiceException(GetErrorResult(ex)); } } }
/// <summary> /// Executes the reqest asynchronous. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="apiRequest">The API request.</param> /// <param name="converter">The converter.</param> /// <param name="customHeaders">The custom headers.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public async Task <Tuple <T, Dictionary <string, string> > > ExecuteRequestAsync <T>(ApiRequest apiRequest, JsonConverter converter, Dictionary <string, string> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { var response = await ExecuteRequestWithResponseAsync <T>(apiRequest, converter, customHeaders, cancellationToken); return(response.Data); }
/// <summary> /// Executes the request. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="apiRequest">The API request.</param> /// <param name="converter">The converter.</param> /// <param name="customHeaders">Custom headers sending with request.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public async Task <T> ExecuteAsync <T>(ApiRequest apiRequest, JsonConverter converter = null, Dictionary <string, string> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { var result = await ExecuteRequestAsync <T>(apiRequest, converter, customHeaders, cancellationToken).ConfigureAwait(false); return(result != null ? result.Item1 : default(T)); }
private static NoteV1 ConvertToNotes(object value) { return(JsonConverter.FromJson <NoteV1>(JsonConverter.ToJson(value))); }
internal static JsonPropertyInfo CreateProperty( Type declaredPropertyType, Type runtimePropertyType, PropertyInfo propertyInfo, Type parentClassType, Type collectionElementType, Type nullableUnderlyingType, JsonConverter converter, ClassType classType, JsonSerializerOptions options) { bool treatAsNullable = nullableUnderlyingType != null; // Obtain the type of the JsonPropertyInfo class to construct. Type propertyInfoClassType; if (treatAsNullable && converter != null) { propertyInfoClassType = typeof(JsonPropertyInfoNullable <,>).MakeGenericType(parentClassType, nullableUnderlyingType); } else { Type typeToConvert = converter?.TypeToConvert; if (typeToConvert == null) { typeToConvert = declaredPropertyType; } // For the covariant case, create JsonPropertyInfoNotNullable. The generic constraints are "where TConverter : TDeclaredProperty". if (runtimePropertyType.IsAssignableFrom(typeToConvert)) { propertyInfoClassType = typeof(JsonPropertyInfoNotNullable <, , ,>).MakeGenericType( parentClassType, declaredPropertyType, runtimePropertyType, typeToConvert); } else { Debug.Assert(typeToConvert.IsAssignableFrom(runtimePropertyType)); // For the contravariant case, create JsonPropertyInfoNotNullableContravariant. The generic constraints are "where TDeclaredProperty : TConverter". propertyInfoClassType = typeof(JsonPropertyInfoNotNullableContravariant <, , ,>).MakeGenericType( parentClassType, declaredPropertyType, runtimePropertyType, typeToConvert); } } // Create the JsonPropertyInfo instance. JsonPropertyInfo jsonPropertyInfo = (JsonPropertyInfo)Activator.CreateInstance( propertyInfoClassType, BindingFlags.Instance | BindingFlags.Public, binder: null, args: null, culture: null); jsonPropertyInfo.Initialize( parentClassType, declaredPropertyType, runtimePropertyType, runtimeClassType: classType, propertyInfo, collectionElementType, converter, treatAsNullable, options); return(jsonPropertyInfo); }
public NullableConverter(JsonConverter <T> converter) { _converter = converter; IsInternalConverterForNumberType = converter.IsInternalConverterForNumberType; }
private object CreateValue(JsonReader reader, Type objectType, JsonContract contract, object existingValue, JsonConverter memberConverter) { JsonConverter converter; if (memberConverter != null) return memberConverter.ReadJson(reader, objectType, GetInternalSerializer()); if (contract != null && contract.Converter != null) return contract.Converter.ReadJson(reader, objectType, GetInternalSerializer()); if (objectType != null && Serializer.HasMatchingConverter(objectType, out converter)) return converter.ReadJson(reader, objectType, GetInternalSerializer()); if (contract is JsonLinqContract) return CreateJToken(reader, contract); do { switch (reader.TokenType) { // populate a typed object or generic dictionary/array // depending upon whether an objectType was supplied case JsonToken.StartObject: return CreateObject(reader, objectType, contract, existingValue); case JsonToken.StartArray: return CreateList(reader, objectType, contract, existingValue, null); case JsonToken.Integer: case JsonToken.Float: case JsonToken.Boolean: case JsonToken.Date: case JsonToken.Bytes: return EnsureType(reader.Value, objectType); case JsonToken.String: // convert empty string to null automatically for nullable types if (string.IsNullOrEmpty((string)reader.Value) && objectType != null && ReflectionUtils.IsNullableType(objectType)) return null; return EnsureType(reader.Value, objectType); case JsonToken.StartConstructor: case JsonToken.EndConstructor: string constructorName = reader.Value.ToString(); return constructorName; case JsonToken.Null: case JsonToken.Undefined: if (objectType == typeof (DBNull)) return DBNull.Value; return EnsureType(reader.Value, objectType); case JsonToken.Raw: return new JRaw((string)reader.Value); case JsonToken.Comment: // ignore break; default: throw new JsonSerializationException("Unexpected token while deserializing object: " + reader.TokenType); } } while (reader.Read()); throw new JsonSerializationException("Unexpected end when deserializing object."); }
private static TValue?ReadUsingMetadata <TValue>(ref Utf8JsonReader reader, JsonTypeInfo jsonTypeInfo) { ReadStack state = default; state.Initialize(jsonTypeInfo); JsonReaderState readerState = reader.CurrentState; if (readerState.Options.CommentHandling == JsonCommentHandling.Allow) { throw new ArgumentException(SR.JsonSerializerDoesNotSupportComments, nameof(reader)); } // Value copy to overwrite the ref on an exception and undo the destructive reads. Utf8JsonReader restore = reader; ReadOnlySpan <byte> valueSpan = default; ReadOnlySequence <byte> valueSequence = default; try { switch (reader.TokenType) { // A new reader was created and has never been read, // so we need to move to the first token. // (or a reader has terminated and we're about to throw) case JsonTokenType.None: // Using a reader loop the caller has identified a property they wish to // hydrate into a JsonDocument. Move to the value first. case JsonTokenType.PropertyName: { if (!reader.Read()) { ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.ExpectedOneCompleteToken); } break; } } switch (reader.TokenType) { // Any of the "value start" states are acceptable. case JsonTokenType.StartObject: case JsonTokenType.StartArray: { long startingOffset = reader.TokenStartIndex; if (!reader.TrySkip()) { ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.NotEnoughData); } long totalLength = reader.BytesConsumed - startingOffset; ReadOnlySequence <byte> sequence = reader.OriginalSequence; if (sequence.IsEmpty) { valueSpan = reader.OriginalSpan.Slice( checked ((int)startingOffset), checked ((int)totalLength)); } else { valueSequence = sequence.Slice(startingOffset, totalLength); } Debug.Assert( reader.TokenType == JsonTokenType.EndObject || reader.TokenType == JsonTokenType.EndArray); break; } // Single-token values case JsonTokenType.Number: case JsonTokenType.True: case JsonTokenType.False: case JsonTokenType.Null: { if (reader.HasValueSequence) { valueSequence = reader.ValueSequence; } else { valueSpan = reader.ValueSpan; } break; } // String's ValueSequence/ValueSpan omits the quotes, we need them back. case JsonTokenType.String: { ReadOnlySequence <byte> sequence = reader.OriginalSequence; if (sequence.IsEmpty) { // Since the quoted string fit in a ReadOnlySpan originally // the contents length plus the two quotes can't overflow. int payloadLength = reader.ValueSpan.Length + 2; Debug.Assert(payloadLength > 1); ReadOnlySpan <byte> readerSpan = reader.OriginalSpan; Debug.Assert( readerSpan[(int)reader.TokenStartIndex] == (byte)'"', $"Calculated span starts with {readerSpan[(int)reader.TokenStartIndex]}"); Debug.Assert( readerSpan[(int)reader.TokenStartIndex + payloadLength - 1] == (byte)'"', $"Calculated span ends with {readerSpan[(int)reader.TokenStartIndex + payloadLength - 1]}"); valueSpan = readerSpan.Slice((int)reader.TokenStartIndex, payloadLength); } else { long payloadLength = 2; if (reader.HasValueSequence) { payloadLength += reader.ValueSequence.Length; } else { payloadLength += reader.ValueSpan.Length; } valueSequence = sequence.Slice(reader.TokenStartIndex, payloadLength); Debug.Assert( valueSequence.First.Span[0] == (byte)'"', $"Calculated sequence starts with {valueSequence.First.Span[0]}"); Debug.Assert( valueSequence.ToArray()[payloadLength - 1] == (byte)'"', $"Calculated sequence ends with {valueSequence.ToArray()[payloadLength - 1]}"); } break; } default: { byte displayByte; if (reader.HasValueSequence) { displayByte = reader.ValueSequence.First.Span[0]; } else { displayByte = reader.ValueSpan[0]; } ThrowHelper.ThrowJsonReaderException( ref reader, ExceptionResource.ExpectedStartOfValueNotFound, displayByte); break; } } } catch (JsonReaderException ex) { reader = restore; // Re-throw with Path information. ThrowHelper.ReThrowWithPath(state, ex); } int length = valueSpan.IsEmpty ? checked ((int)valueSequence.Length) : valueSpan.Length; byte[] rented = ArrayPool <byte> .Shared.Rent(length); Span <byte> rentedSpan = rented.AsSpan(0, length); try { if (valueSpan.IsEmpty) { valueSequence.CopyTo(rentedSpan); } else { valueSpan.CopyTo(rentedSpan); } JsonReaderOptions originalReaderOptions = readerState.Options; var newReader = new Utf8JsonReader(rentedSpan, originalReaderOptions); JsonConverter jsonConverter = state.Current.JsonPropertyInfo !.ConverterBase; TValue? value = ReadCore <TValue>(jsonConverter, ref newReader, jsonTypeInfo.Options, ref state); // The reader should have thrown if we have remaining bytes. Debug.Assert(newReader.BytesConsumed == length); return(value); } catch (JsonException) { reader = restore; throw; } finally { rentedSpan.Clear(); ArrayPool <byte> .Shared.Return(rented); } }
public void HandleMessage(MessageEvent e) { var data = e.Data; string cmd = data.cmd; switch (cmd) { case CmdSetLogLevel: Logger.LogLevel = data.value; break; case CmdSetMasterVolume: _player.MasterVolume = data.value; break; case CmdSetMetronomeVolume: _player.MetronomeVolume = data.value; break; case CmdSetPlaybackSpeed: _player.PlaybackSpeed = data.value; break; case CmdSetTickPosition: _player.TickPosition = data.value; break; case CmdSetTimePosition: _player.TimePosition = data.value; break; case CmdSetPlaybackRange: _player.PlaybackRange = data.value; break; case CmdSetIsLooping: _player.IsLooping = data.value; break; case CmdPlay: _player.Play(); break; case CmdPause: _player.Pause(); break; case CmdPlayPause: _player.PlayPause(); break; case CmdStop: _player.Stop(); break; case CmdLoadSoundFontBytes: _player.LoadSoundFont(data.data); break; case CmdLoadMidi: _player.LoadMidi(JsonConverter.JsObjectToMidiFile(data.midi)); break; case CmdSetChannelMute: _player.SetChannelMute(data.channel, data.mute); break; case CmdSetChannelSolo: _player.SetChannelSolo(data.channel, data.solo); break; case CmdSetChannelVolume: _player.SetChannelVolume(data.channel, data.volume); break; case CmdSetChannelProgram: _player.SetChannelProgram(data.channel, data.program); break; case CmdResetChannelStates: _player.ResetChannelStates(); break; } }
/// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { if (converters != null && converters.Length > 0 && _value != null) { JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); if (matchingConverter != null) { matchingConverter.WriteJson(writer, _value, new JsonSerializer()); return; } } switch (_valueType) { case JTokenType.Comment: writer.WriteComment((_value != null) ? _value.ToString() : null); return; case JTokenType.Raw: writer.WriteRawValue((_value != null) ? _value.ToString() : null); return; case JTokenType.Null: writer.WriteNull(); return; case JTokenType.Undefined: writer.WriteUndefined(); return; case JTokenType.Integer: #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE) if (_value is BigInteger) { writer.WriteValue((BigInteger)_value); } else #endif writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture)); return; case JTokenType.Float: if (_value is decimal) { writer.WriteValue((decimal)_value); } else if (_value is double) { writer.WriteValue((double)_value); } else if (_value is float) { writer.WriteValue((float)_value); } else { writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture)); } return; case JTokenType.String: writer.WriteValue((_value != null) ? _value.ToString() : null); return; case JTokenType.Boolean: writer.WriteValue(Convert.ToBoolean(_value, CultureInfo.InvariantCulture)); return; case JTokenType.Date: #if !NET20 if (_value is DateTimeOffset) { writer.WriteValue((DateTimeOffset)_value); } else #endif writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture)); return; case JTokenType.Bytes: writer.WriteValue((byte[])_value); return; case JTokenType.Guid: case JTokenType.Uri: case JTokenType.TimeSpan: writer.WriteValue((_value != null) ? _value.ToString() : null); return; } throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", _valueType, "Unexpected token type."); }
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { if (value == null) { writer.WriteNull(); return; } JsonConverter converter = ((member != null) ? member.Converter : null) ?? ((containerProperty != null) ? containerProperty.ItemConverter : null) ?? ((containerContract != null) ? containerContract.ItemConverter : null) ?? 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) ? (IDictionary)value : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty); break; #if !(NET35 || NET20 || PORTABLE40) case JsonContractType.Dynamic: SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty); break; #endif #if !(DOTNET || PORTABLE40 || PORTABLE) 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; } }
public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options) { return(_valueConverter ?? (_valueConverter = new DictionaryConverterInner(options))); }
public TvShow MapToTvShow(HttpResponseMessage seriesInfo) { string tvShowDataParsed = seriesInfo.Content.ReadAsStringAsync().Result; return(JsonConverter.ConvertJsonToObject <TvShow>(tvShowDataParsed)); }
internal abstract void InitializeForTypeInfo( Type declaredType, JsonTypeInfo runtimeTypeInfo, JsonConverter converter, JsonSerializerOptions options);
private object CreateValue(JsonReader reader, Type objectType, object existingValue, JsonConverter memberConverter) { JsonConverter converter; if (memberConverter != null) return memberConverter.ReadJson(reader, objectType, GetInternalSerializer()); if (objectType != null && Serializer.HasClassConverter(objectType, out converter)) return converter.ReadJson(reader, objectType, GetInternalSerializer()); if (objectType != null && Serializer.HasMatchingConverter(objectType, out converter)) return converter.ReadJson(reader, objectType, GetInternalSerializer()); if (objectType == typeof (JsonRaw)) return JsonRaw.Create(reader); do { switch (reader.TokenType) { // populate a typed object or generic dictionary/array // depending upon whether an objectType was supplied case JsonToken.StartObject: return CreateObject(reader, objectType, existingValue); case JsonToken.StartArray: return CreateList(reader, objectType, existingValue, null); case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Date: // convert empty string to null automatically ///////////////////////// //MKT:2009-11-21 why in the name of god would you wan tto do that? //orig: //if (reader.Value is string && // string.IsNullOrEmpty((string)reader.Value) && // objectType != null && // ReflectionUtils.IsNullable(objectType)) // return null; if (reader.Value is string && reader.Value==null && objectType != null && ReflectionUtils.IsNullable(objectType)) return null; ///////////////////////// return EnsureType(reader.Value, objectType); case JsonToken.StartConstructor: case JsonToken.EndConstructor: string constructorName = reader.Value.ToString(); return constructorName; case JsonToken.Null: case JsonToken.Undefined: if (objectType == typeof (DBNull)) return DBNull.Value; return null; case JsonToken.Comment: // ignore break; default: throw new JsonSerializationException("Unexpected token while deserializing object: " + reader.TokenType); } } while (reader.Read()); throw new JsonSerializationException("Unexpected end when deserializing object."); }
/// <summary> /// Creates metadata for a primitive or a type with a custom converter. /// </summary> /// <typeparam name="T">The generic type definition.</typeparam> /// <returns>A <see cref="JsonTypeInfo{T}"/> instance representing the type.</returns> public static JsonTypeInfo <T> CreateValueInfo <T>(JsonSerializerOptions options, JsonConverter converter) { JsonTypeInfo <T> info = new JsonTypeInfoInternal <T>(options); info.PropertyInfoForTypeInfo = CreateJsonPropertyInfoForClassInfo(typeof(T), info, converter, options); return(info); }
// Token: 0x06000BC8 RID: 3016 // RVA: 0x00044828 File Offset: 0x00042A28 private bool SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target) { bool flag; object value; JsonContract contract; bool flag2; if (this.CalculatePropertyDetails(property, ref propertyConverter, containerContract, containerProperty, reader, target, out flag, out value, out contract, out flag2)) { return false; } object obj; if (propertyConverter != null && propertyConverter.CanRead) { if (!flag2 && target != null && property.Readable) { value = property.ValueProvider.GetValue(target); } obj = this.DeserializeConvertable(propertyConverter, reader, property.PropertyType, value); } else { obj = this.CreateValueInternal(reader, property.PropertyType, contract, property, containerContract, containerProperty, flag ? value : null); } if ((!flag || obj != value) && this.ShouldSetPropertyValue(property, obj)) { property.ValueProvider.SetValue(target, obj); if (property.SetIsSpecified != null) { if (this.TraceWriter != null && this.TraceWriter.LevelFilter >= TraceLevel.Verbose) { this.TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, StringUtils.FormatWith("IsSpecified for property '{0}' on {1} set to true.", CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType)), null); } property.SetIsSpecified(target, true); } return true; } return flag; }
public static JsonSerializerSettings AddConverter(this JsonSerializerSettings settings, JsonConverter converter) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } Contract.EndContractBlock(); settings.Converters.Add(converter); return(settings); }
// Token: 0x06000BD8 RID: 3032 // RVA: 0x00045C64 File Offset: 0x00043E64 private object DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, object existingValue) { if (this.TraceWriter != null && this.TraceWriter.LevelFilter >= TraceLevel.Info) { this.TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, StringUtils.FormatWith("Started deserializing {0} with converter {1}.", CultureInfo.InvariantCulture, objectType, converter.GetType())), null); } object result = converter.ReadJson(reader, objectType, existingValue, this.GetInternalSerializer()); if (this.TraceWriter != null && this.TraceWriter.LevelFilter >= TraceLevel.Info) { this.TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, StringUtils.FormatWith("Finished deserializing {0} with converter {1}.", CultureInfo.InvariantCulture, objectType, converter.GetType())), null); } return result; }
/// <summary> /// Gets a batch of changes to synchronize when given batch size, /// destination knowledge, and change data retriever parameters. /// </summary> /// <returns>A DbSyncContext object that will be used to retrieve the modified data.</returns> public virtual async Task <(SyncContext, BatchInfo)> GetSnapshotAsync( SyncContext context, SyncSet schema, string snapshotDirectory, CancellationToken cancellationToken, IProgress <ProgressArgs> progress = null) { // TODO : Get a snapshot based on scope name var sb = new StringBuilder(); var underscore = ""; if (context.Parameters != null) { foreach (var p in context.Parameters.OrderBy(p => p.Name)) { var cleanValue = new string(p.Value.ToString().Where(char.IsLetterOrDigit).ToArray()); var cleanName = new string(p.Name.Where(char.IsLetterOrDigit).ToArray()); sb.Append($"{underscore}{cleanName}_{cleanValue}"); underscore = "_"; } } var directoryName = sb.ToString(); directoryName = string.IsNullOrEmpty(directoryName) ? "ALL" : directoryName; this.Orchestrator.logger.LogDebug(SyncEventsId.GetSnapshot, new { DirectoryName = directoryName }); // cleansing scope name var directoryScopeName = new string(context.ScopeName.Where(char.IsLetterOrDigit).ToArray()); // Get full path var directoryFullPath = Path.Combine(snapshotDirectory, directoryScopeName, directoryName); // if no snapshot present, just return null value. if (!Directory.Exists(directoryFullPath)) { this.Orchestrator.logger.LogDebug(SyncEventsId.DirectoryNotExists, new { DirectoryPath = directoryFullPath }); return(context, null); } // Serialize on disk. var jsonConverter = new JsonConverter <BatchInfo>(); var summaryFileName = Path.Combine(directoryFullPath, "summary.json"); BatchInfo batchInfo = null; // Create the schema changeset var changesSet = new SyncSet(); // Create a Schema set without readonly columns, attached to memory changes foreach (var table in schema.Tables) { SyncAdapter.CreateChangesTable(schema.Tables[table.TableName, table.SchemaName], changesSet); } using (var fs = new FileStream(summaryFileName, FileMode.Open, FileAccess.Read)) { this.Orchestrator.logger.LogDebug(SyncEventsId.LoadSnapshotSummary, new { FileName = summaryFileName }); batchInfo = await jsonConverter.DeserializeAsync(fs).ConfigureAwait(false); this.Orchestrator.logger.LogDebug(SyncEventsId.LoadSnapshotSummary, batchInfo); } batchInfo.SanitizedSchema = changesSet; return(context, batchInfo); }
public MemberMap SetConverter(JsonConverter converter) { _jsonProperty.Converter = converter; _jsonProperty.MemberConverter = converter; return(this); }
/// <summary> /// update configuration object with tables desc from server database /// </summary> public virtual async Task <(SyncContext, BatchInfo)> CreateSnapshotAsync(SyncContext context, SyncSet schema, SyncSetup setup, DbConnection connection, DbTransaction transaction, string snapshotDirectory, int batchSize, long remoteClientTimestamp, CancellationToken cancellationToken, IProgress <ProgressArgs> progress = null) { // create local directory if (!Directory.Exists(snapshotDirectory)) { this.Orchestrator.logger.LogDebug(SyncEventsId.CreateDirectory, new { SnapshotDirectory = snapshotDirectory }); Directory.CreateDirectory(snapshotDirectory); } // cleansing scope name var directoryScopeName = new string(context.ScopeName.Where(char.IsLetterOrDigit).ToArray()); var directoryFullPath = Path.Combine(snapshotDirectory, directoryScopeName); // create local directory with scope inside if (!Directory.Exists(directoryFullPath)) { this.Orchestrator.logger.LogDebug(SyncEventsId.CreateDirectory, new { DirectoryFullPath = directoryFullPath }); Directory.CreateDirectory(directoryFullPath); } // numbers of batch files generated var batchIndex = 0; // create the in memory changes set var changesSet = new SyncSet(); var sb = new StringBuilder(); var underscore = ""; if (context.Parameters != null) { foreach (var p in context.Parameters.OrderBy(p => p.Name)) { var cleanValue = new string(p.Value.ToString().Where(char.IsLetterOrDigit).ToArray()); var cleanName = new string(p.Name.Where(char.IsLetterOrDigit).ToArray()); sb.Append($"{underscore}{cleanName}_{cleanValue}"); underscore = "_"; } } var directoryName = sb.ToString(); directoryName = string.IsNullOrEmpty(directoryName) ? "ALL" : directoryName; // batchinfo generate a schema clone with scope columns if needed var batchInfo = new BatchInfo(false, schema, directoryFullPath, directoryName); // Delete directory if already exists directoryFullPath = Path.Combine(directoryFullPath, directoryName); if (Directory.Exists(directoryFullPath)) { this.Orchestrator.logger.LogDebug(SyncEventsId.DropDirectory, new { DirectoryFullPath = directoryFullPath }); Directory.Delete(directoryFullPath, true); } foreach (var syncTable in schema.Tables) { var tableBuilder = this.GetTableBuilder(syncTable, setup); var syncAdapter = tableBuilder.CreateSyncAdapter(); // launch interceptor if any await this.Orchestrator.InterceptAsync(new TableChangesSelectingArgs(context, syncTable, connection, transaction), cancellationToken).ConfigureAwait(false); // Get Select initialize changes command var selectIncrementalChangesCommand = await this.GetSelectChangesCommandAsync(context, syncAdapter, syncTable, true, connection, transaction); // Set parameters this.SetSelectChangesCommonParameters(context, syncTable, null, true, 0, selectIncrementalChangesCommand); // log this.Orchestrator.logger.LogDebug(SyncEventsId.CreateSnapshot, new { SelectChangesCommandText = selectIncrementalChangesCommand.CommandText, ExcludingScopeId = Guid.Empty, IsNew = true, LastTimestamp = 0 }); // Get the reader using (var dataReader = selectIncrementalChangesCommand.ExecuteReader()) { // memory size total double rowsMemorySize = 0L; // Create a chnages table with scope columns var changesSetTable = SyncAdapter.CreateChangesTable(schema.Tables[syncTable.TableName, syncTable.SchemaName], changesSet); while (dataReader.Read()) { // Create a row from dataReader var row = CreateSyncRowFromReader(dataReader, changesSetTable); // Add the row to the changes set changesSetTable.Rows.Add(row); // Log trace row this.Orchestrator.logger.LogTrace(SyncEventsId.CreateSnapshot, row); var fieldsSize = ContainerTable.GetRowSizeFromDataRow(row.ToArray()); var finalFieldSize = fieldsSize / 1024d; if (finalFieldSize > batchSize) { throw new RowOverSizedException(finalFieldSize.ToString()); } // Calculate the new memory size rowsMemorySize += finalFieldSize; // Next line if we don't reach the batch size yet. if (rowsMemorySize <= batchSize) { continue; } // add changes to batchinfo await batchInfo.AddChangesAsync(changesSet, batchIndex, false, this.Orchestrator).ConfigureAwait(false); this.Orchestrator.logger.LogDebug(SyncEventsId.CreateBatch, changesSet); // increment batch index batchIndex++; // we know the datas are serialized here, so we can flush the set changesSet.Clear(); // Recreate an empty ContainerSet and a ContainerTable changesSet = new SyncSet(); changesSetTable = SyncAdapter.CreateChangesTable(schema.Tables[syncTable.TableName, syncTable.SchemaName], changesSet); // Init the row memory size rowsMemorySize = 0L; } } //selectIncrementalChangesCommand.Dispose(); } if (changesSet != null && changesSet.HasTables) { await batchInfo.AddChangesAsync(changesSet, batchIndex, true, this.Orchestrator).ConfigureAwait(false); this.Orchestrator.logger.LogDebug(SyncEventsId.CreateBatch, changesSet); } // Check the last index as the last batch batchInfo.EnsureLastBatch(); batchInfo.Timestamp = remoteClientTimestamp; // Serialize on disk. var jsonConverter = new JsonConverter <BatchInfo>(); var summaryFileName = Path.Combine(directoryFullPath, "summary.json"); using (var f = new FileStream(summaryFileName, FileMode.CreateNew, FileAccess.ReadWrite)) { this.Orchestrator.logger.LogDebug(SyncEventsId.CreateSnapshotSummary, batchInfo); var bytes = await jsonConverter.SerializeAsync(batchInfo).ConfigureAwait(false); f.Write(bytes, 0, bytes.Length); } return(context, batchInfo); }
public void TryConvertingFromStreamNullToSimpleObject() { JsonConverter<ObjectWithName> converter = new JsonConverter<ObjectWithName>(); ObjectWithName objectExpected = converter.ConvertFrom(null); Assert.IsTrue(objectExpected.Name == new ObjectWithName().Name); }
public SoftwareVersion GetSoftwareVersion(string json) { return(JsonConverter.DeserializeObject <SoftwareVersion>(json)); }
private object DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, object existingValue) { object value = converter.ReadJson(reader, objectType, existingValue, GetInternalSerializer()); return value; }
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value) { if (ShouldWriteReference(value, null)) { WriteReference(writer, value); } else { if (!CheckForCircularReference(value, null)) return; SerializeStack.Add(value); converter.WriteJson(writer, value, GetInternalSerializer()); SerializeStack.RemoveAt(SerializeStack.Count - 1); } }
private Dictionary <string, object> GetParseConversionData() { string json = System.Web.HttpContext.Current.Server.UrlDecode(Request.Content.ReadAsStringAsync().Result.Replace("%22", "%2522").Replace("%2B", "%252B").Replace("+", "%2B")); return(JsonConverter.Deserialize(json)); }
public JsonValueTrimmable(TValue value, JsonConverter <TValue> converter, JsonNodeOptions?options = null) : base(value, options) { _converter = converter; }
internal sealed override bool OnTryRead( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, [MaybeNullWhen(false)] out TCollection value) { bool shouldReadPreservedReferences = options.ReferenceHandling.ShouldReadPreservedReferences(); if (!state.SupportContinuation && !shouldReadPreservedReferences) { // Fast path that avoids maintaining state variables and dealing with preserved references. if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } CreateCollection(ref state); JsonConverter <TValue> elementConverter = GetElementConverter(ref state); if (elementConverter.CanUseDirectReadOrWrite) { // Process all elements. while (true) { // Read the key name. reader.ReadWithVerify(); if (reader.TokenType == JsonTokenType.EndObject) { break; } if (reader.TokenType != JsonTokenType.PropertyName) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } state.Current.JsonPropertyNameAsString = reader.GetString(); // Read the value and add. reader.ReadWithVerify(); TValue element = elementConverter.Read(ref reader, typeof(TValue), options); Add(element, options, ref state); } } else { // Process all elements. while (true) { // Read the key name. reader.ReadWithVerify(); if (reader.TokenType == JsonTokenType.EndObject) { break; } if (reader.TokenType != JsonTokenType.PropertyName) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } state.Current.JsonPropertyNameAsString = reader.GetString(); reader.ReadWithVerify(); // Get the value from the converter and add it. elementConverter.TryRead(ref reader, typeof(TValue), options, ref state, out TValue element); Add(element, options, ref state); } } } else { // Slower path that supports continuation and preserved references. if (state.Current.ObjectState == StackFrameObjectState.None) { if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.StartToken; } // Handle the metadata properties. if (shouldReadPreservedReferences && state.Current.ObjectState < StackFrameObjectState.MetadataPropertyValue) { if (JsonSerializer.ResolveMetadata(this, ref reader, ref state)) { if (state.Current.ObjectState == StackFrameObjectState.MetadataRefPropertyEndObject) { value = (TCollection)state.Current.ReturnValue !; return(true); } } else { value = default !;
private static async ValueTask <TValue> ReadAsync <TValue>( Stream utf8Json, Type returnType, JsonSerializerOptions?options, CancellationToken cancellationToken) { if (options == null) { options = JsonSerializerOptions.s_defaultOptions; } ReadStack state = default; state.Initialize(returnType, options, supportContinuation: true); JsonConverter converter = state.Current.JsonPropertyInfo !.ConverterBase; var readerState = new JsonReaderState(options.GetReaderOptions()); // todo: https://github.com/dotnet/runtime/issues/32355 int utf8BomLength = JsonConstants.Utf8Bom.Length; byte[] buffer = ArrayPool <byte> .Shared.Rent(Math.Max(options.DefaultBufferSize, utf8BomLength)); int bytesInBuffer = 0; long totalBytesRead = 0; int clearMax = 0; bool isFirstIteration = true; try { while (true) { // Read from the stream until either our buffer is filled or we hit EOF. // Calling ReadCore is relatively expensive, so we minimize the number of times // we need to call it. bool isFinalBlock = false; while (true) { int bytesRead = await utf8Json.ReadAsync( #if BUILDING_INBOX_LIBRARY buffer.AsMemory(bytesInBuffer), #else buffer, bytesInBuffer, buffer.Length - bytesInBuffer, #endif cancellationToken).ConfigureAwait(false); if (bytesRead == 0) { isFinalBlock = true; break; } totalBytesRead += bytesRead; bytesInBuffer += bytesRead; if (bytesInBuffer == buffer.Length) { break; } } if (bytesInBuffer > clearMax) { clearMax = bytesInBuffer; } int start = 0; if (isFirstIteration) { isFirstIteration = false; // Handle the UTF-8 BOM if present Debug.Assert(buffer.Length >= JsonConstants.Utf8Bom.Length); if (buffer.AsSpan().StartsWith(JsonConstants.Utf8Bom)) { start += utf8BomLength; bytesInBuffer -= utf8BomLength; } } // Process the data available TValue value = ReadCore <TValue>( ref readerState, isFinalBlock, new ReadOnlySpan <byte>(buffer, start, bytesInBuffer), options, ref state, converter); Debug.Assert(state.BytesConsumed <= bytesInBuffer); int bytesConsumed = checked ((int)state.BytesConsumed); bytesInBuffer -= bytesConsumed; if (isFinalBlock) { // The reader should have thrown if we have remaining bytes. Debug.Assert(bytesInBuffer == 0); return(value); } // Check if we need to shift or expand the buffer because there wasn't enough data to complete deserialization. if ((uint)bytesInBuffer > ((uint)buffer.Length / 2)) { // We have less than half the buffer available, double the buffer size. byte[] dest = ArrayPool <byte> .Shared.Rent((buffer.Length < (int.MaxValue / 2))?buffer.Length * 2 : int.MaxValue); // Copy the unprocessed data to the new buffer while shifting the processed bytes. Buffer.BlockCopy(buffer, bytesConsumed + start, dest, 0, bytesInBuffer); new Span <byte>(buffer, 0, clearMax).Clear(); ArrayPool <byte> .Shared.Return(buffer); clearMax = bytesInBuffer; buffer = dest; } else if (bytesInBuffer != 0) { // Shift the processed bytes to the beginning of buffer to make more room. Buffer.BlockCopy(buffer, bytesConsumed + start, buffer, 0, bytesInBuffer); } } } finally { // Clear only what we used and return the buffer to the pool new Span <byte>(buffer, 0, clearMax).Clear(); ArrayPool <byte> .Shared.Return(buffer); } }
private void SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonReader reader, object target) { if (property.Ignored) { reader.Skip(); return; } object currentValue = null; bool useExistingValue = false; bool gottenCurrentValue = false; ObjectCreationHandling objectCreationHandling = property.ObjectCreationHandling.GetValueOrDefault(Serializer.ObjectCreationHandling); if ((objectCreationHandling == ObjectCreationHandling.Auto || objectCreationHandling == ObjectCreationHandling.Reuse) && (reader.TokenType == JsonToken.StartArray || reader.TokenType == JsonToken.StartObject) && property.Readable) { currentValue = property.ValueProvider.GetValue(target); gottenCurrentValue = true; useExistingValue = (currentValue != null && !property.PropertyType.IsArray && !ReflectionUtils.InheritsGenericDefinition(property.PropertyType, typeof (ReadOnlyCollection<>)) && !property.PropertyType.IsValueType()); } if (!property.Writable && !useExistingValue) { reader.Skip(); return; } // test tokentype here because null might not be convertable to some types, e.g. ignoring null when applied to DateTime if (property.NullValueHandling.GetValueOrDefault(Serializer.NullValueHandling) == NullValueHandling.Ignore && reader.TokenType == JsonToken.Null) { reader.Skip(); return; } // test tokentype here because default value might not be convertable to actual type, e.g. default of "" for DateTime if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer.DefaultValueHandling), DefaultValueHandling.Ignore) && JsonReader.IsPrimitiveToken(reader.TokenType) && MiscellaneousUtils.ValueEquals(reader.Value, property.DefaultValue)) { reader.Skip(); return; } object existingValue = (useExistingValue) ? currentValue : null; object value = CreateValueProperty(reader, property, propertyConverter, target, gottenCurrentValue, existingValue); // always set the value if useExistingValue is false, // otherwise also set it if CreateValue returns a new value compared to the currentValue // this could happen because of a JsonConverter against the type if ((!useExistingValue || value != currentValue) && ShouldSetPropertyValue(property, value)) { property.ValueProvider.SetValue(target, value); if (property.SetIsSpecified != null) property.SetIsSpecified(target, true); } }
private JsonConverter GetConverter(JsonContract contract, JsonConverter memberConverter) { JsonConverter converter = null; if (memberConverter != null) { // member attribute converter converter = memberConverter; } else if (contract != null) { JsonConverter matchingConverter; if (contract.Converter != null) // class attribute converter converter = contract.Converter; else if ((matchingConverter = Serializer.GetMatchingConverter(contract.UnderlyingType)) != null) // passed in converters converter = matchingConverter; else if (contract.InternalConverter != null) // internally specified converter converter = contract.InternalConverter; } return converter; }
public List <S_CandleItemData> Query( string itemCode , string gubun = "D" //M : 15Min, H : Hour, D : Day, W : Week, M : Month ) { this.ItemCode = itemCode; int round = ItemCodeUtil.GetItemCodeRoundNum(ItemCode); Task.Factory.StartNew(() => { try { string symbol = "169"; if (itemCode == "DJI@DJI") { symbol = "169"; } else if (itemCode == "NAS@IXIC") { symbol = "14958"; } else if (itemCode == "SPI@SPX") { symbol = "166"; } else if (itemCode == "HSI@HSI") { symbol = "179"; } else if (itemCode == "SHS@000002") { symbol = "40820"; } else if (itemCode == "NII@NI225") { symbol = "178"; } string resolution = gubun; if (gubun == "H" || gubun == "1H") { resolution = "60"; } else if (gubun == "2H") { resolution = "120"; } else if (gubun == "4H") { resolution = "240"; } else if (gubun == "5H") { resolution = "300"; } else if (gubun == "M" || gubun == "1M") { resolution = "1"; } else if (gubun == "5M") { resolution = "5"; } else if (gubun == "15M") { resolution = "15"; } else if (gubun == "30M") { resolution = "30"; } Int32 from = (Int32)(DateTime.UtcNow.AddYears(-2).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; Int32 to = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; if (gubun == "M" || gubun == "1M") { from = (Int32)(DateTime.UtcNow.AddDays(-1).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; to = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } else if (gubun == "5M") { from = (Int32)(DateTime.UtcNow.AddDays(-5).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; to = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } else if (gubun == "15M") { from = (Int32)(DateTime.UtcNow.AddDays(-15).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; to = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } else if (gubun == "30M") { from = (Int32)(DateTime.UtcNow.AddMonths(-1).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; to = (Int32)(DateTime.UtcNow.AddDays(1).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } else if (gubun == "H" || gubun == "1H") { from = (Int32)(DateTime.UtcNow.AddMonths(-2).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; to = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } else if (gubun == "2H") { from = (Int32)(DateTime.UtcNow.AddMonths(-4).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; to = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } else if (gubun == "4H") { from = (Int32)(DateTime.UtcNow.AddMonths(-8).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; to = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } else if (gubun == "5H") { from = (Int32)(DateTime.UtcNow.AddMonths(-10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; to = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } else if (gubun == "W") { from = (Int32)(DateTime.UtcNow.AddYears(-5).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; to = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } else if (gubun == "M") { from = (Int32)(DateTime.UtcNow.AddYears(-10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; to = (Int32)(DateTime.UtcNow.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } string urlPath = $"https://tvc4.forexpros.com/1cc1f0b6f392b9fad2b50b7aebef1f7c/1601866558/18/18/88/history?symbol={symbol}&resolution={resolution}&from={from}&to={to}"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlPath); request.MaximumAutomaticRedirections = 4; request.MaximumResponseHeadersLength = 4; request.Credentials = CredentialCache.DefaultCredentials; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream receiveStream = response.GetResponseStream(); StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); string content = readStream.ReadToEnd(); var dyObj = JsonConverter.JsonToDynamicObject(content); int cnt = dyObj.t.Count; for (int i = 0; i < cnt; i++) { Int64 t = dyObj.t[i]; double o = dyObj.o[i]; double c = dyObj.c[i]; double h = dyObj.h[i]; double l = dyObj.l[i]; DateTime cTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(t); //Console.WriteLine($"DT : {cTime.ToLongDateString()} O : {Math.Round(o, 2)}, H : {Math.Round(h, 2)}, L : {Math.Round(l, 2)}, C : {Math.Round(c, 2)}"); S_CandleItemData data = new S_CandleItemData(); data.DTime = cTime; data.ItemCode = ItemCode; data.OpenPrice = (Single)Math.Round(o, round); data.HighPrice = (Single)Math.Round(h, round); data.LowPrice = (Single)Math.Round(l, round); data.ClosePrice = (Single)Math.Round(c, round); data.Volume = 0; returnList.Add(data); } } catch (Exception ex) { string err = ex.Message; } finally { manualEvent.Set(); } }); manualEvent.WaitOne(); return(returnList); }
private object CreateValueProperty(JsonReader reader, JsonProperty property, JsonConverter propertyConverter, object target, bool gottenCurrentValue, object currentValue) { JsonContract contract; JsonConverter converter; if (property.PropertyContract == null) property.PropertyContract = GetContractSafe(property.PropertyType); if (currentValue == null) { contract = property.PropertyContract; converter = propertyConverter; } else { contract = GetContractSafe(currentValue.GetType()); if (contract != property.PropertyContract) converter = GetConverter(contract, property.MemberConverter); else converter = propertyConverter; } Type objectType = property.PropertyType; if (converter != null && converter.CanRead) { if (!gottenCurrentValue && target != null && property.Readable) currentValue = property.ValueProvider.GetValue(target); return converter.ReadJson(reader, objectType, currentValue, GetInternalSerializer()); } return CreateValueInternal(reader, objectType, contract, property, currentValue); }
private object CreateValueNonProperty(JsonReader reader, Type objectType, JsonContract contract, JsonConverter converter) { if (converter != null && converter.CanRead) return converter.ReadJson(reader, objectType, null, GetInternalSerializer()); return CreateValueInternal(reader, objectType, contract, null, null); }
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); } }
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty)) { WriteReference(writer, value); } else { if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty)) return; _serializeStack.Add(value); converter.WriteJson(writer, value, GetInternalSerializer()); _serializeStack.RemoveAt(_serializeStack.Count - 1); } }
private bool CalculatePropertyDetails(JsonProperty property, ref JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target, out bool useExistingValue, out object currentValue, out JsonContract propertyContract, out bool gottenCurrentValue) { currentValue = null; useExistingValue = false; propertyContract = null; gottenCurrentValue = false; if (property.Ignored) return true; JsonToken tokenType = reader.TokenType; if (property.PropertyContract == null) property.PropertyContract = GetContractSafe(property.PropertyType); ObjectCreationHandling objectCreationHandling = property.ObjectCreationHandling.GetValueOrDefault(Serializer._objectCreationHandling); if ((objectCreationHandling != ObjectCreationHandling.Replace) && (tokenType == JsonToken.StartArray || tokenType == JsonToken.StartObject) && property.Readable) { currentValue = property.ValueProvider.GetValue(target); gottenCurrentValue = true; if (currentValue != null) { propertyContract = GetContractSafe(currentValue.GetType()); useExistingValue = (!propertyContract.IsReadOnlyOrFixedSize && !propertyContract.UnderlyingType.IsValueType()); } } if (!property.Writable && !useExistingValue) return true; // test tokentype here because null might not be convertable to some types, e.g. ignoring null when applied to DateTime if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore && tokenType == JsonToken.Null) return true; // test tokentype here because default value might not be convertable to actual type, e.g. default of "" for DateTime if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore) && !HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate) && JsonReader.IsPrimitiveToken(tokenType) && MiscellaneousUtils.ValueEquals(reader.Value, property.GetResolvedDefaultValue())) return true; if (currentValue == null) { propertyContract = property.PropertyContract; } else { propertyContract = GetContractSafe(currentValue.GetType()); if (propertyContract != property.PropertyContract) propertyConverter = GetConverter(propertyContract, property.MemberConverter, containerContract, containerProperty); } return false; }
private object DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, object existingValue) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Started deserializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, objectType, converter.GetType())), null); object value = converter.ReadJson(reader, objectType, existingValue, GetInternalSerializer()); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Finished deserializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, objectType, converter.GetType())), null); return value; }
private bool SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target) { object currentValue; bool useExistingValue; JsonContract propertyContract; bool gottenCurrentValue; if (CalculatePropertyDetails(property, ref propertyConverter, containerContract, containerProperty, reader, target, out useExistingValue, out currentValue, out propertyContract, out gottenCurrentValue)) return false; object value; if (propertyConverter != null && propertyConverter.CanRead) { if (!gottenCurrentValue && target != null && property.Readable) currentValue = property.ValueProvider.GetValue(target); value = DeserializeConvertable(propertyConverter, reader, property.PropertyType, currentValue); } else { value = CreateValueInternal(reader, property.PropertyType, propertyContract, property, containerContract, containerProperty, (useExistingValue) ? currentValue : null); } // always set the value if useExistingValue is false, // otherwise also set it if CreateValue returns a new value compared to the currentValue // this could happen because of a JsonConverter against the type if ((!useExistingValue || value != currentValue) && ShouldSetPropertyValue(property, value)) { property.ValueProvider.SetValue(target, value); if (property.SetIsSpecified != null) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "IsSpecified for property '{0}' on {1} set to true.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType)), null); property.SetIsSpecified(target, true); } return true; } // the value wasn't set be JSON was populated onto the existing value return useExistingValue; }
private bool CalculatePropertyDetails(JsonProperty property, ref JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target, out bool useExistingValue, out object currentValue, out JsonContract propertyContract, out bool gottenCurrentValue) { currentValue = null; useExistingValue = false; propertyContract = null; gottenCurrentValue = false; if (property.Ignored) { reader.Skip(); return true; } ObjectCreationHandling objectCreationHandling = property.ObjectCreationHandling.GetValueOrDefault(Serializer.ObjectCreationHandling); if ((objectCreationHandling == ObjectCreationHandling.Auto || objectCreationHandling == ObjectCreationHandling.Reuse) && (reader.TokenType == JsonToken.StartArray || reader.TokenType == JsonToken.StartObject) && property.Readable) { currentValue = property.ValueProvider.GetValue(target); gottenCurrentValue = true; useExistingValue = (currentValue != null && !property.PropertyType.IsArray && !ReflectionUtils.InheritsGenericDefinition(property.PropertyType, typeof (ReadOnlyCollection<>)) && !property.PropertyType.IsValueType()); } if (!property.Writable && !useExistingValue) { reader.Skip(); return true; } // test tokentype here because null might not be convertable to some types, e.g. ignoring null when applied to DateTime if (property.NullValueHandling.GetValueOrDefault(Serializer.NullValueHandling) == NullValueHandling.Ignore && reader.TokenType == JsonToken.Null) { reader.Skip(); return true; } // test tokentype here because default value might not be convertable to actual type, e.g. default of "" for DateTime if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer.DefaultValueHandling), DefaultValueHandling.Ignore) && JsonReader.IsPrimitiveToken(reader.TokenType) && MiscellaneousUtils.ValueEquals(reader.Value, property.GetResolvedDefaultValue())) { reader.Skip(); return true; } if (property.PropertyContract == null) property.PropertyContract = GetContractSafe(property.PropertyType); if (currentValue == null) { propertyContract = property.PropertyContract; } else { propertyContract = GetContractSafe(currentValue.GetType()); if (propertyContract != property.PropertyContract) propertyConverter = GetConverter(propertyContract, property.MemberConverter, containerContract, containerProperty); } return false; }
private void SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target) { object currentValue; bool useExistingValue; JsonContract propertyContract; bool gottenCurrentValue; if (CalculatePropertyDetails(property, ref propertyConverter, containerContract, containerProperty, reader, target, out useExistingValue, out currentValue, out propertyContract, out gottenCurrentValue)) return; object value; if (propertyConverter != null && propertyConverter.CanRead) { if (!gottenCurrentValue && target != null && property.Readable) currentValue = property.ValueProvider.GetValue(target); value = propertyConverter.ReadJson(reader, property.PropertyType, currentValue, GetInternalSerializer()); } else { value = CreateValueInternal(reader, property.PropertyType, propertyContract, property, containerContract, containerProperty, (useExistingValue) ? currentValue : null); } // always set the value if useExistingValue is false, // otherwise also set it if CreateValue returns a new value compared to the currentValue // this could happen because of a JsonConverter against the type if ((!useExistingValue || value != currentValue) && ShouldSetPropertyValue(property, value)) { property.ValueProvider.SetValue(target, value); if (property.SetIsSpecified != null) property.SetIsSpecified(target, true); } }
private bool ReadForType(JsonReader reader, Type t, JsonConverter propertyConverter) { // don't read properties with converters as a specific value // the value might be a string which will then get converted which will error if read as date for example bool hasConverter = (GetConverter(GetContractSafe(t), propertyConverter) != null); if (hasConverter) return reader.Read(); if (t == typeof(byte[])) { reader.ReadAsBytes(); return true; } else if ((t == typeof(decimal) || t == typeof(decimal?))) { reader.ReadAsDecimal(); return true; } #if !NET20 else if ((t == typeof(DateTimeOffset) || t == typeof(DateTimeOffset?))) { reader.ReadAsDateTimeOffset(); return true; } #endif do { if (!reader.Read()) return false; } while (reader.TokenType == JsonToken.Comment); return true; }
/// <summary> /// Simple Vector3 Serialization /// </summary> public void SerializeVector3() { LogStart("Vector3 Serialization"); try { var v = new Vector3(2, 4, 6); var converters = new JsonConverter[] { new Vector3Converter() }; var serialized = JsonConvert.SerializeObject(v, Formatting.None, converters); LogSerialized(serialized); var v2 = JsonConvert.DeserializeObject<Vector3>(serialized); LogResult("4", v2.y); if (v2.y != v.y) { DisplayFail("Vector3 Serialization", BAD_RESULT_MESSAGE); } DisplaySuccess("Vector3 Serialization"); } catch(Exception ex) { DisplayFail("Vector3 Serialization", ex.Message); } LogEnd(1); }