/// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            bool nullable = ReflectionUtils.IsNullableType(objectType);

#if !NET20
            Type t = (nullable)
                ? Nullable.GetUnderlyingType(objectType)
                : objectType;
#endif

            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullableType(objectType))
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                }

                return(null);
            }

            if (reader.TokenType == JsonToken.Date)
            {
#if !NET20
                if (t == typeof(DateTimeOffset))
                {
                    return((reader.Value is DateTimeOffset) ? reader.Value : new DateTimeOffset((DateTime)reader.Value));
                }

                // converter is expected to return a DateTime
                if (reader.Value is DateTimeOffset)
                {
                    return(((DateTimeOffset)reader.Value).DateTime);
                }
#endif

                return(reader.Value);
            }

            if (reader.TokenType != JsonToken.String)
            {
                throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }

            string dateText = reader.Value.ToString();

            if (string.IsNullOrEmpty(dateText) && nullable)
            {
                return(null);
            }

#if !NET20
            if (t == typeof(DateTimeOffset))
            {
                if (!string.IsNullOrEmpty(_dateTimeFormat))
                {
                    return(DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles));
                }
                else
                {
                    return(DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles));
                }
            }
#endif

            if (!string.IsNullOrEmpty(_dateTimeFormat))
            {
                return(DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles));
            }
            else
            {
                return(DateTime.Parse(dateText, Culture, _dateTimeStyles));
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            bool isNullable = ReflectionUtils.IsNullableType(objectType);
            Type t          = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType;

            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullableType(objectType))
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                }

                return(null);
            }

            try
            {
                if (reader.TokenType == JsonToken.String)
                {
                    string enumText = reader.Value.ToString();
                    if (enumText == string.Empty && isNullable)
                    {
                        return(null);
                    }

                    string finalEnumText;

                    BidirectionalDictionary <string, string> map = GetEnumNameMap(t);
                    if (enumText.IndexOf(',') != -1)
                    {
                        string[] names = enumText.Split(',');
                        for (int i = 0; i < names.Length; i++)
                        {
                            string name = names[i].Trim();

                            names[i] = ResolvedEnumName(map, name);
                        }

                        finalEnumText = string.Join(", ", names);
                    }
                    else
                    {
                        finalEnumText = ResolvedEnumName(map, enumText);
                    }

                    return(Enum.Parse(t, finalEnumText, true));
                }

                if (reader.TokenType == JsonToken.Integer)
                {
                    if (!AllowIntegerValues)
                    {
                        throw JsonSerializationException.Create(reader, "Integer value {0} is not allowed.".FormatWith(CultureInfo.InvariantCulture, reader.Value));
                    }

                    return(ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t));
                }
            }
            catch (Exception ex)
            {
                throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.FormatValueForPrint(reader.Value), objectType), ex);
            }

            // we don't actually expect to get here.
            throw JsonSerializationException.Create(reader, "Unexpected token {0} when parsing enum.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
        }
        private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
        {
            if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
            {
                return(true);
            }

            ReferenceLoopHandling?referenceLoopHandling = null;

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

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

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

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

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

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

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

                    return(false);

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

                    return(true);
                }
            }

            return(true);
        }
        private IJsonValue CreateJsonValue(JsonReader reader)
        {
            while (reader.TokenType == JsonToken.Comment)
            {
                if (!reader.Read())
                {
                    throw JsonSerializationException.Create(reader, "Unexpected end.");
                }
            }

            switch (reader.TokenType)
            {
            case JsonToken.StartObject:
            {
                return(CreateJsonObject(reader));
            }

            case JsonToken.StartArray:
            {
                JsonArray a = new JsonArray();

                while (reader.Read())
                {
                    switch (reader.TokenType)
                    {
                    case JsonToken.EndArray:
                        return(a);

                    default:
                        IJsonValue value = CreateJsonValue(reader);
                        a.Add(value);
                        break;
                    }
                }
            }
            break;

            case JsonToken.Integer:
            case JsonToken.Float:
                return(JsonValue.CreateNumberValue(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture)));

            case JsonToken.String:
                return(JsonValue.CreateStringValue(reader.Value.ToString()));

            case JsonToken.Boolean:
                return(JsonValue.CreateBooleanValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture)));

            case JsonToken.Null:
                // surely there is a better way to create a null value than this?
                return(JsonValue.Parse("null"));

            case JsonToken.Date:
                return(JsonValue.CreateStringValue(reader.Value.ToString()));

            case JsonToken.Bytes:
                return(JsonValue.CreateStringValue(reader.Value.ToString()));

            default:
                throw JsonSerializationException.Create(reader, "Unexpected or unsupported token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }

            throw JsonSerializationException.Create(reader, "Unexpected end.");
        }
Esempio n. 5
0
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return(null);
            }

            UnionCase caseInfo = null;
            string    caseName = null;
            JArray    fields   = null;

            // start object
            ReadAndAssert(reader);

            while (reader.TokenType == JsonToken.PropertyName)
            {
                string propertyName = reader.Value.ToString();
                if (string.Equals(propertyName, CasePropertyName, StringComparison.OrdinalIgnoreCase))
                {
                    ReadAndAssert(reader);

                    Union union = UnionCache.Get(objectType);

                    caseName = reader.Value.ToString();

                    caseInfo = union.Cases.SingleOrDefault(c => c.Name == caseName);

                    if (caseInfo == null)
                    {
                        throw JsonSerializationException.Create(reader, "No union type found with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
                    }
                }
                else if (string.Equals(propertyName, FieldsPropertyName, StringComparison.OrdinalIgnoreCase))
                {
                    ReadAndAssert(reader);
                    if (reader.TokenType != JsonToken.StartArray)
                    {
                        throw JsonSerializationException.Create(reader, "Union fields must been an array.");
                    }

                    fields = (JArray)JToken.ReadFrom(reader);
                }
                else
                {
                    throw JsonSerializationException.Create(reader, "Unexpected property '{0}' found when reading union.".FormatWith(CultureInfo.InvariantCulture, propertyName));
                }

                ReadAndAssert(reader);
            }

            if (caseInfo == null)
            {
                throw JsonSerializationException.Create(reader, "No '{0}' property with union name found.".FormatWith(CultureInfo.InvariantCulture, CasePropertyName));
            }

            object[] typedFieldValues = new object[caseInfo.Fields.Length];

            if (caseInfo.Fields.Length > 0 && fields == null)
            {
                throw JsonSerializationException.Create(reader, "No '{0}' property with union fields found.".FormatWith(CultureInfo.InvariantCulture, FieldsPropertyName));
            }

            if (fields != null)
            {
                if (caseInfo.Fields.Length != fields.Count)
                {
                    throw JsonSerializationException.Create(reader, "The number of field values does not match the number of properties definied by union '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
                }


                for (int i = 0; i < fields.Count; i++)
                {
                    JToken       t             = fields[i];
                    PropertyInfo fieldProperty = caseInfo.Fields[i];

                    typedFieldValues[i] = t.ToObject(fieldProperty.PropertyType, serializer);
                }
            }

            object[] args = { typedFieldValues };

            return(caseInfo.Constructor.Invoke(args));
        }
Esempio n. 6
0
        private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            contract.InvokeOnSerializing(value, Serializer.Context);

            _serializeStack.Add(value);

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

            int initialDepth = writer.Top;

            foreach (JsonProperty property in contract.Properties)
            {
                try
                {
                    if (!property.Ignored && property.Readable && ShouldSerialize(property, value) && IsSpecified(property, value))
                    {
                        if (property.PropertyContract == null)
                        {
                            property.PropertyContract = Serializer.ContractResolver.ResolveContract(property.PropertyType);
                        }

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

                        if (ShouldWriteProperty(memberValue, property))
                        {
                            string propertyName = property.PropertyName;

                            if (ShouldWriteReference(memberValue, property, memberContract, contract, member))
                            {
                                writer.WritePropertyName(propertyName);
                                WriteReference(writer, memberValue);
                                continue;
                            }

                            if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member))
                            {
                                continue;
                            }

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

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

            writer.WriteEndObject();

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            contract.InvokeOnSerialized(value, Serializer.Context);
        }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return(null);
            }

            object matchingCaseInfo = null;
            string caseName         = null;
            JArray fields           = null;

            // start object
            ReadAndAssert(reader);

            while (reader.TokenType == JsonToken.PropertyName)
            {
                string propertyName = reader.Value.ToString();
                if (string.Equals(propertyName, CasePropertyName, StringComparison.OrdinalIgnoreCase))
                {
                    ReadAndAssert(reader);

                    IEnumerable cases = (IEnumerable)FSharpUtils.GetUnionCases(null, objectType, null);

                    caseName = reader.Value.ToString();

                    foreach (object c in cases)
                    {
                        if ((string)FSharpUtils.GetUnionCaseInfoName(c) == caseName)
                        {
                            matchingCaseInfo = c;
                            break;
                        }
                    }

                    if (matchingCaseInfo == null)
                    {
                        throw JsonSerializationException.Create(reader, "No union type found with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
                    }
                }
                else if (string.Equals(propertyName, FieldsPropertyName, StringComparison.OrdinalIgnoreCase))
                {
                    ReadAndAssert(reader);
                    if (reader.TokenType != JsonToken.StartArray)
                    {
                        throw JsonSerializationException.Create(reader, "Union fields must been an array.");
                    }

                    fields = (JArray)JToken.ReadFrom(reader);
                }
                else
                {
                    throw JsonSerializationException.Create(reader, "Unexpected property '{0}' found when reading union.".FormatWith(CultureInfo.InvariantCulture, propertyName));
                }

                ReadAndAssert(reader);
            }

            if (matchingCaseInfo == null)
            {
                throw JsonSerializationException.Create(reader, "No '{0}' property with union name found.".FormatWith(CultureInfo.InvariantCulture, CasePropertyName));
            }
            if (fields == null)
            {
                throw JsonSerializationException.Create(reader, "No '{0}' property with union fields found.".FormatWith(CultureInfo.InvariantCulture, FieldsPropertyName));
            }

            PropertyInfo[] fieldProperties = (PropertyInfo[])FSharpUtils.GetUnionCaseInfoFields(matchingCaseInfo);

            if (fieldProperties.Length != fields.Count)
            {
                throw JsonSerializationException.Create(reader, "The number of field values does not match the number of properties definied by union '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
            }

            object[] typedFieldValues = new object[fieldProperties.Length];
            for (int i = 0; i < fields.Count; i++)
            {
                JToken       t             = fields[i];
                PropertyInfo fieldProperty = fieldProperties[i];

                typedFieldValues[i] = t.ToObject(fieldProperty.PropertyType);
            }

            return(FSharpUtils.MakeUnion(null, matchingCaseInfo, typedFieldValues, null));
        }
        private Dictionary <string, string> ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager)
        {
            string xmlValue;
            string str;
            string str1;
            Dictionary <string, string> strs = new Dictionary <string, string>();
            bool flag  = false;
            bool flag1 = false;

            if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null && reader.TokenType != JsonToken.Boolean && reader.TokenType != JsonToken.Integer && reader.TokenType != JsonToken.Float && reader.TokenType != JsonToken.Date && reader.TokenType != JsonToken.StartConstructor)
            {
                while (!flag && !flag1 && reader.Read())
                {
                    JsonToken tokenType = reader.TokenType;
                    if (tokenType == JsonToken.PropertyName)
                    {
                        string str2 = reader.Value.ToString();
                        if (string.IsNullOrEmpty(str2))
                        {
                            flag = true;
                        }
                        else
                        {
                            char chr = str2[0];
                            if (chr != '$')
                            {
                                if (chr != '@')
                                {
                                    flag = true;
                                }
                                else
                                {
                                    str2 = str2.Substring(1);
                                    reader.Read();
                                    xmlValue = this.ConvertTokenToXmlValue(reader);
                                    strs.Add(str2, xmlValue);
                                    if (!this.IsNamespaceAttribute(str2, out str))
                                    {
                                        continue;
                                    }
                                    manager.AddNamespace(str, xmlValue);
                                }
                            }
                            else if (str2 == "$values" || str2 == "$id" || str2 == "$ref" || str2 == "$type" || str2 == "$value")
                            {
                                string str3 = manager.LookupPrefix("http://james.newtonking.com/projects/json");
                                if (str3 == null)
                                {
                                    int?nullable = null;
                                    while (manager.LookupNamespace(string.Concat("json", nullable)) != null)
                                    {
                                        nullable = new int?(nullable.GetValueOrDefault() + 1);
                                    }
                                    str3 = string.Concat("json", nullable);
                                    strs.Add(string.Concat("xmlns:", str3), "http://james.newtonking.com/projects/json");
                                    manager.AddNamespace(str3, "http://james.newtonking.com/projects/json");
                                }
                                if (str2 != "$values")
                                {
                                    str2 = str2.Substring(1);
                                    reader.Read();
                                    if (!JsonTokenUtils.IsPrimitiveToken(reader.TokenType))
                                    {
                                        throw JsonSerializationException.Create(reader, string.Concat("Unexpected JsonToken: ", reader.TokenType));
                                    }
                                    if (reader.Value != null)
                                    {
                                        str1 = reader.Value.ToString();
                                    }
                                    else
                                    {
                                        str1 = null;
                                    }
                                    xmlValue = str1;
                                    strs.Add(string.Concat(str3, ":", str2), xmlValue);
                                }
                                else
                                {
                                    flag = true;
                                }
                            }
                            else
                            {
                                flag = true;
                            }
                        }
                    }
                    else if (tokenType == JsonToken.Comment)
                    {
                        flag1 = true;
                    }
                    else
                    {
                        if (tokenType != JsonToken.EndObject)
                        {
                            throw JsonSerializationException.Create(reader, string.Concat("Unexpected JsonToken: ", reader.TokenType));
                        }
                        flag1 = true;
                    }
                }
            }
            return(strs);
        }
        private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, IXmlNode currentNode)
        {
            do
            {
                JsonToken tokenType = reader.TokenType;
                switch (tokenType)
                {
                case JsonToken.StartConstructor:
                {
                    string str = reader.Value.ToString();
                    while (reader.Read())
                    {
                        if (reader.TokenType != JsonToken.EndConstructor)
                        {
                            this.DeserializeValue(reader, document, manager, str, currentNode);
                        }
                        else
                        {
                            goto Label0;
                        }
                    }
                    goto Label0;
                }

                case JsonToken.PropertyName:
                {
                    if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null)
                    {
                        throw JsonSerializationException.Create(reader, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.");
                    }
                    string str1 = reader.Value.ToString();
                    reader.Read();
                    if (reader.TokenType != JsonToken.StartArray)
                    {
                        this.DeserializeValue(reader, document, manager, str1, currentNode);
                        continue;
                    }
                    else
                    {
                        int num = 0;
                        while (reader.Read() && reader.TokenType != JsonToken.EndArray)
                        {
                            this.DeserializeValue(reader, document, manager, str1, currentNode);
                            num++;
                        }
                        if (num != 1 || !this.WriteArrayAttribute)
                        {
                            continue;
                        }
                        List <IXmlNode> .Enumerator enumerator = currentNode.ChildNodes.GetEnumerator();
                        try
                        {
                            while (enumerator.MoveNext())
                            {
                                IXmlElement current = enumerator.Current as IXmlElement;
                                if (current == null || !(current.LocalName == str1))
                                {
                                    continue;
                                }
                                this.AddJsonArrayAttribute(current, document);
                                goto Label0;
                            }
                            continue;
                        }
                        finally
                        {
                            ((IDisposable)enumerator).Dispose();
                        }
                    }
                    break;
                }

                case JsonToken.Comment:
                {
                    currentNode.AppendChild(document.CreateComment((string)reader.Value));
                    continue;
                }

                default:
                {
                    if (tokenType == JsonToken.EndObject || tokenType == JsonToken.EndArray)
                    {
                        break;
                    }
                    else
                    {
                        throw JsonSerializationException.Create(reader, string.Concat("Unexpected JsonToken when deserializing node: ", reader.TokenType));
                    }
                }
                }
                return;

Label0:
            }while (reader.TokenType == JsonToken.PropertyName || reader.Read());
        }
Esempio n. 10
0
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object?ReadJson(
            JsonReader reader,
            Type objectType,
            object?existingValue,
            JsonSerializer serializer
            )
        {
            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullableType(objectType))
                {
                    throw JsonSerializationException.Create(
                              reader,
                              "Cannot convert null value to KeyValuePair."
                              );
                }

                return(null);
            }

            object?key   = null;
            object?value = null;

            reader.ReadAndAssert();

            Type t = ReflectionUtils.IsNullableType(objectType)
              ? Nullable.GetUnderlyingType(objectType)
              : objectType;

            ReflectionObject reflectionObject = ReflectionObjectPerType.Get(t);
            JsonContract     keyContract      = serializer.ContractResolver.ResolveContract(
                reflectionObject.GetType(KeyName)
                );
            JsonContract valueContract = serializer.ContractResolver.ResolveContract(
                reflectionObject.GetType(ValueName)
                );

            while (reader.TokenType == JsonToken.PropertyName)
            {
                string propertyName = reader.Value !.ToString();
                if (string.Equals(propertyName, KeyName, StringComparison.OrdinalIgnoreCase))
                {
                    reader.ReadForTypeAndAssert(keyContract, false);

                    key = serializer.Deserialize(reader, keyContract.UnderlyingType);
                }
                else if (string.Equals(propertyName, ValueName, StringComparison.OrdinalIgnoreCase))
                {
                    reader.ReadForTypeAndAssert(valueContract, false);

                    value = serializer.Deserialize(reader, valueContract.UnderlyingType);
                }
                else
                {
                    reader.Skip();
                }

                reader.ReadAndAssert();
            }

            return(reflectionObject.Creator !(key, value));
        }
Esempio n. 11
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            bool flag = ReflectionUtils.IsNullableType(objectType);
            Type type = flag ? Nullable.GetUnderlyingType(objectType) : objectType;

            if (reader.TokenType != JsonToken.Null)
            {
                try
                {
                    if (reader.TokenType == JsonToken.String)
                    {
                        string text = reader.Value.ToString();
                        object result;
                        if (text == string.Empty && flag)
                        {
                            result = null;
                            return(result);
                        }
                        BidirectionalDictionary <string, string> enumNameMap = this.GetEnumNameMap(type);
                        string value;
                        if (text.IndexOf(',') != -1)
                        {
                            string[] array = text.Split(new char[]
                            {
                                ','
                            });
                            for (int i = 0; i < array.Length; i++)
                            {
                                string enumText = array[i].Trim();
                                array[i] = StringEnumConverter.ResolvedEnumName(enumNameMap, enumText);
                            }
                            value = string.Join(", ", array);
                        }
                        else
                        {
                            value = StringEnumConverter.ResolvedEnumName(enumNameMap, text);
                        }
                        result = Enum.Parse(type, value, true);
                        return(result);
                    }
                    else if (reader.TokenType == JsonToken.Integer)
                    {
                        if (!this.AllowIntegerValues)
                        {
                            throw JsonSerializationException.Create(reader, "Integer value {0} is not allowed.".FormatWith(CultureInfo.InvariantCulture, reader.Value));
                        }
                        object result = ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, type);
                        return(result);
                    }
                }
                catch (Exception ex)
                {
                    throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.FormatValueForPrint(reader.Value), objectType), ex);
                }
                throw JsonSerializationException.Create(reader, "Unexpected token {0} when parsing enum.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }
            if (!ReflectionUtils.IsNullableType(objectType))
            {
                throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
            }
            return(null);
        }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object?ReadJson(
            JsonReader reader,
            Type objectType,
            object?existingValue,
            JsonSerializer serializer
            )
        {
            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullable(objectType))
                {
                    throw JsonSerializationException.Create(
                              reader,
                              "Cannot convert null value to {0}.".FormatWith(
                                  CultureInfo.InvariantCulture,
                                  objectType
                                  )
                              );
                }

                return(null);
            }

            if (
                reader.TokenType != JsonToken.StartConstructor ||
                !string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal)
                )
            {
                throw JsonSerializationException.Create(
                          reader,
                          "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(
                              CultureInfo.InvariantCulture,
                              reader.TokenType,
                              reader.Value
                              )
                          );
            }

            if (
                !JavaScriptUtils.TryGetDateFromConstructorJson(
                    reader,
                    out DateTime d,
                    out string?errorMessage
                    )
                )
            {
                throw JsonSerializationException.Create(reader, errorMessage);
            }

#if HAVE_DATE_TIME_OFFSET
            Type t =
                (ReflectionUtils.IsNullableType(objectType))
                    ? Nullable.GetUnderlyingType(objectType)
                    : objectType;
            if (t == typeof(DateTimeOffset))
            {
                return(new DateTimeOffset(d));
            }
#endif
            return(d);
        }