Esempio n. 1
0
        private bool ValidateType(Subschema schema, object value)
        {
            var type = MPJson.GetType(value);

            switch (type)
            {
            case JsonType.Object:
                if ((schema.Flags & SchemaFlags.TypeObject) == 0)
                {
                    break;
                }
                return(ValidateObject(schema, (KeyValuePair <string, object>[])value));

            case JsonType.Array:
                if ((schema.Flags & SchemaFlags.TypeArray) == 0)
                {
                    break;
                }
                return(ValidateArray(schema, (object[])value));

            case JsonType.Number:
                double d = Convert.ToDouble(value);
                if ((schema.Flags & SchemaFlags.TypeNumber) == 0 &&
                    ((schema.Flags & SchemaFlags.TypeInteger) == 0 || d != Math.Floor(d)))
                {
                    break;
                }
                return(ValidateNumber(schema, d));

            case JsonType.String:
                if ((schema.Flags & SchemaFlags.TypeString) != 0)
                {
                    return(ValidateString(schema, (string)value));
                }

                if (this.CoerceStringsToValues)
                {
                    var str = (string)value;
                    if ((schema.Flags & (SchemaFlags.TypeNumber | SchemaFlags.TypeInteger)) != 0 &&
                        double.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out d) &&
                        (0 != (schema.Flags & SchemaFlags.TypeNumber) || d == Math.Floor(d)))
                    {
                        return(ValidateNumber(schema, d));
                    }

                    if ((schema.Flags & SchemaFlags.TypeBoolean) != 0 &&
                        string.Equals(str, str.Length == 4 ? JsonParser.TrueKeyword : JsonParser.FalseKeyword, StringComparison.OrdinalIgnoreCase))
                    {
                        return(true);
                    }
                }

                break;

            case JsonType.Boolean:
                if ((schema.Flags & SchemaFlags.TypeBoolean) == 0)
                {
                    break;
                }
                return(true);

            case JsonType.Null:
                if ((schema.Flags & SchemaFlags.TypeNull) == 0)
                {
                    break;
                }
                return(true);
            }

            if (!IsRecordingErrors)
            {
                return(false);
            }

            return((schema.Flags & SchemaFlags.TypeAll) != 0
                ? ReportError(
                       ErrorType.Type,
                       schema,
                       actual: KeywordUtils.GetTypeText(type),
                       expected: schema.GetValidTypes(),
                       instance: value)
                : ReportError(ErrorType.None, actual: value));
        }