Beispiel #1
0
        /// <summary>
        /// Constructs a new JsonReader instance. This is a stack-only type.
        /// </summary>
        /// <param name="data">The <see cref="Span{byte}"/> value to consume. </param>
        /// <param name="encoder">An encoder used for decoding bytes from <paramref name="data"/> into characters.</param>
        public Utf8JsonReader(ReadOnlySpan <byte> data)
        {
            _isRetry          = false;
            _containerMask    = 0;
            Depth             = 0;
            _inObject         = false;
            _searchedNextLast = false;
            _stack            = null;
            TokenType         = JsonTokenType.None;

            _reader          = default;
            _isSingleSegment = true;
            _buffer          = data;
            CurrentIndex     = 0;
            TokenStartIndex  = CurrentIndex;
            _maxDepth        = StackFreeMaxDepth;
            Value            = ReadOnlySpan <byte> .Empty;
            ValueType        = JsonValueType.Unknown;
            _isFinalBlock    = true;
            _isSingleValue   = false;

#if UseInstrumented
            _lineNumber = 1;
            _position   = 0;
#endif
        }
Beispiel #2
0
        public Utf8JsonReader(ReadOnlySpan <byte> data, bool isFinalBlock, JsonReaderState state = default)
        {
            _isRetry          = state != default;
            _containerMask    = state._containerMask;
            Depth             = state._depth;
            _inObject         = state._inObject;
            _searchedNextLast = state._searchedNextLast;
            _stack            = state._stack;
            TokenType         = state._tokenType;

            _reader          = default;
            _isSingleSegment = true;
            _buffer          = data;
            CurrentIndex     = 0;
            TokenStartIndex  = CurrentIndex;
            _maxDepth        = StackFreeMaxDepth;
            Value            = ReadOnlySpan <byte> .Empty;
            ValueType        = JsonValueType.Unknown;
            _isFinalBlock    = isFinalBlock;
            _isSingleValue   = false;

#if UseInstrumented
            _lineNumber = 1;
            _position   = 0;
#endif
        }
Beispiel #3
0
        internal JsonValue(string text, JsonValueType type)
        {
            text.VerifyNotNull(nameof(text));

            Text = text;
            Type = type;
        }
Beispiel #4
0
        public Utf8String GetValue(JsonValueType type)
        {
            SkipEmpty();
            switch (type)
            {
            case JsonValueType.String:
                return(ReadStringValue());

            case JsonValueType.Number:
                return(ReadNumberValue());

            case JsonValueType.True:
                return(ReadTrueValue());

            case JsonValueType.False:
                return(ReadFalseValue());

            case JsonValueType.Null:
                return(ReadNullValue());

            case JsonValueType.Object:
            case JsonValueType.Array:
                return(Utf8String.Empty);

            default:
                throw new ArgumentException("Invalid json value type '" + type + "'.");
            }
        }
Beispiel #5
0
        public JsonValue(JsonValueType type, object value)
        {
            Type = type;
            switch (type)
            {
            case JsonValueType.String:
                Value = Convert.ToString(value);
                break;

            case JsonValueType.Integer:
                Value = Convert.ToInt64(value);
                break;

            case JsonValueType.Float:
                Value = Convert.ToDouble(value);
                break;

            case JsonValueType.Date:
                Value = Convert.ToDateTime(value);
                break;

            default:
                Value = value;
                break;
            }
        }
Beispiel #6
0
 public JsonValue(StringSegment segment, JsonValueType valueType, int parentIndex)
 {
     Segment     = segment;
     ValueType   = valueType;
     ParentIndex = parentIndex;
     //UnityEngine.Debug.LogFormat("{0}", this.ToString());
 }
        // currently we don't support List or Arrays for TDataItem
        //protected override bool OnArrayItemDetected(JsonReader reader)
        //{
        //    return base.OnArrayItemDetected(reader);
        //}

        protected override void OnBasicItemDetected(string item, JsonValueType itemType)
        {
            var x = Activator.CreateInstance <TDataItem>();

            x = (TDataItem)System.Convert.ChangeType(item, typeof(TDataItem));
            items.Add(x);
        }
Beispiel #8
0
 public JsonValue(JsonDynamicObject obj)
 {
     //TODO: no spans on the heap
     //_value = default(Utf8Span);
     _object = obj;
     _type   = JsonValueType.Object;
 }
Beispiel #9
0
 public JsonValue(Utf8Span value, JsonValueType type = JsonValueType.String)
 {
     //TODO: no spans on the heap
     //_value = value;
     _object = null;
     _type   = type;
 }
Beispiel #10
0
 public JsonValue(JsonValueType type)
 {
     _type = type;
     //TODO: no spans on the heap
     //_value = default(Utf8Span);
     _object = null;
 }
Beispiel #11
0
        private static Value.ValueType MapValueType(JsonValueType type)
        {
            switch (type)
            {
            case JsonValueType.False:
                return(Value.ValueType.False);

            case JsonValueType.True:
                return(Value.ValueType.True);

            case JsonValueType.Null:
                return(Value.ValueType.Null);

            case JsonValueType.Number:
                return(Value.ValueType.Number);

            case JsonValueType.String:
                return(Value.ValueType.String);

            case JsonValueType.Array:
                return(Value.ValueType.Array);

            case JsonValueType.Object:
                return(Value.ValueType.Object);

            default:
                throw new ArgumentException();
            }
        }
Beispiel #12
0
 TinyJsonObject(TinyJsonArray array)
 {
     this             = default;
     Type             = JsonValueType.Array;
     m_Data           = array.m_Data;
     m_ArrayRefHandle = array.m_ArrayRefHandle;
 }
Beispiel #13
0
        public JsonValue(string value)
        {
            ArgumentUtils.AssertNotNull(value, "value");

            this.type  = JsonValueType.String;
            this.value = value;
        }
Beispiel #14
0
        private static void JsonLabEmptyLoopHelper(byte[] data)
        {
            var json = new Utf8JsonReader(data);

            while (json.Read())
            {
                JsonTokenType tokenType = json.TokenType;
                switch (tokenType)
                {
                case JsonTokenType.StartObject:
                case JsonTokenType.EndObject:
                case JsonTokenType.StartArray:
                case JsonTokenType.EndArray:
                    break;

                case JsonTokenType.PropertyName:
                    break;

                case JsonTokenType.Value:
                    JsonValueType valueType = json.ValueType;
                    switch (valueType)
                    {
                    case JsonValueType.Unknown:
                        break;

                    case JsonValueType.Object:
                        break;

                    case JsonValueType.Array:
                        break;

                    case JsonValueType.Number:
                        break;

                    case JsonValueType.String:
                        break;

                    case JsonValueType.True:
                        break;

                    case JsonValueType.False:
                        break;

                    case JsonValueType.Null:
                        break;
                    }
                    break;

                case JsonTokenType.None:
                    break;

                case JsonTokenType.Comment:
                    break;

                default:
                    throw new ArgumentException();
                }
            }
        }
Beispiel #15
0
 TinyJsonObject(FixedString4096 value)
 {
     this        = default;
     Type        = JsonValueType.String;
     m_StringVal = new UnsafeList <FixedString4096>(1, Allocator.Persistent)
     {
         value
     };
 }
Beispiel #16
0
 public static bool TryGetValueType(object value, out JsonValueType valueType, JsonConfig config = null)
 {
     if (value is null)
     {
         valueType = JsonValueType.Null;
         return(true);
     }
     return(TryGetValueType(value.GetType(), out valueType, config ?? JsonConfig.Default));
 }
Beispiel #17
0
 /// <summary>
 /// Creates a copy of a <see cref="JsonValue"/>.
 /// </summary>
 public JsonValue(JsonValue other)
 {
     _arrayValue  = other._arrayValue;
     _objectValue = other._objectValue;
     _numberValue = other._numberValue;
     _stringValue = other._stringValue;
     _boolValue   = other._boolValue;
     Type         = other.Type;
 }
Beispiel #18
0
        private static byte[] JsonLabReturnBytesHelper(byte[] data, SymbolTable symbolTable, out int length, int utf16Multiplier = 1)
        {
            byte[] outputArray = new byte[data.Length];

            Span <byte> destination = outputArray;
            var         json        = new JsonReader(data, symbolTable);

            while (json.Read())
            {
                JsonTokenType       tokenType = json.TokenType;
                ReadOnlySpan <byte> valueSpan = json.Value;
                switch (tokenType)
                {
                case JsonTokenType.PropertyName:
                    valueSpan.CopyTo(destination);
                    destination[valueSpan.Length] = (byte)',';
                    destination[valueSpan.Length + 1 * utf16Multiplier] = (byte)' ';
                    destination = destination.Slice(valueSpan.Length + 2 * utf16Multiplier);
                    break;

                case JsonTokenType.Value:
                    JsonValueType valueType = json.ValueType;

                    switch (valueType)
                    {
                    case JsonValueType.True:
                        destination[0] = (byte)'T';
                        destination[1 * utf16Multiplier] = (byte)'r';
                        destination[2 * utf16Multiplier] = (byte)'u';
                        destination[3 * utf16Multiplier] = (byte)'e';
                        destination = destination.Slice(4 * utf16Multiplier);
                        break;

                    case JsonValueType.False:
                        destination[0] = (byte)'F';
                        destination[1 * utf16Multiplier] = (byte)'a';
                        destination[2 * utf16Multiplier] = (byte)'l';
                        destination[3 * utf16Multiplier] = (byte)'s';
                        destination[4 * utf16Multiplier] = (byte)'e';
                        destination = destination.Slice(5 * utf16Multiplier);
                        break;
                    }

                    valueSpan.CopyTo(destination);
                    destination[valueSpan.Length] = (byte)',';
                    destination[valueSpan.Length + 1 * utf16Multiplier] = (byte)' ';
                    destination = destination.Slice(valueSpan.Length + 2 * utf16Multiplier);
                    break;

                default:
                    break;
                }
            }
            length = outputArray.Length - destination.Length;
            return(outputArray);
        }
        /// <summary>
        /// Creates value with the specified type and raw string representation.
        /// </summary>
        /// <param name="type">The type of the value, that can be Null, Boolean or Number only.</param>
        /// <param name="raw">The value raw string representation.</param>
        public JsonValue(JsonValueType type, string raw)
        {
            if (type == JsonValueType.Object || type == JsonValueType.Array)
            {
                throw new ArgumentException("The type of the value cannot be Object or Array.", nameof(type));
            }

            Type = type;
            Raw  = raw ?? throw new ArgumentNullException(nameof(raw));
        }
        /// <summary>
        /// Json 데이터가 포함된 문자열에서 Json 값을 변환하고, 변환된 값을 반환합니다.
        /// </summary>
        /// <param name="s">Json 데이터가 포함된 문자열입니다.</param>
        /// <param name="isArrayElement">배열 요소인지의 여부를 나타냅니다. 문자열 또는 키-값 쌍의 경우 무시됩니다.</param>
        /// <param name="p">변환 작업이 시작될 문자열 내 인덱스입니다.</param>
        /// <param name="p_new">변환 작업이 끝나는 문자열 내 인덱스가 저장될 변수입니다.</param>
        /// <returns>변환된 Json 값입니다.</returns>
        public static object Convert(string s, bool isArrayElement, int p, out int p_new)
        {
            JsonValueType valueType = s[p].GetValueType();

            if (!cachedConvertCallbacks.ContainsKey(valueType))
            {
                throw new InvalidJsonFormatException($"잘못된 Json 값 형식입니다. (valueType = {valueType})");
            }
            return(cachedConvertCallbacks[valueType](s, isArrayElement, p, out p_new));
        }
Beispiel #21
0
 /// <summary>
 /// Creates a <see cref="JsonValue"/> from a JSON object.
 /// </summary>
 public JsonValue(JsonObject o)
 {
     if (o != null)
     {
         Object = o;
     }
     else
     {
         Type = JsonValueType.Null;
     }
 }
Beispiel #22
0
 /// <summary>
 /// Creates a <see cref="JsonValue"/> from a numeric value.
 /// </summary>
 public JsonValue(double?n)
 {
     if (n != null)
     {
         Number = n.Value;
     }
     else
     {
         Type = JsonValueType.Null;
     }
 }
Beispiel #23
0
 /// <summary>
 /// Creates a <see cref="JsonValue"/> from a boolean.
 /// </summary>
 public JsonValue(bool?b)
 {
     if (b != null)
     {
         Boolean = b.Value;
     }
     else
     {
         Type = JsonValueType.Null;
     }
 }
        /// <summary>
        /// Returns a <see cref="JsonArray"/> containing only the <see cref="JsonValue"/>s of a specified type from a given <see cref="JsonArray"/>.
        /// </summary>
        /// <param name="arr">The array to search</param>
        /// <param name="type">The type of value to return</param>
        /// <returns>A <see cref="JsonArray"/> containing only the <see cref="JsonValue"/>s of a specified type</returns>
        public static JsonArray OfType(this JsonArray arr, JsonValueType type)
        {
            if (arr == null)
            {
                return(null);
            }
            var retVal = new JsonArray();

            retVal.AddRange(arr.Where(j => j.Type == type));
            return(retVal);
        }
Beispiel #25
0
        public DbRow(JsonValueType jsonType, int location, int sizeOrLength = UnknownSize, int numberOfRows = 1)
        {
            Debug.Assert(jsonType >= JsonValueType.Object && jsonType <= JsonValueType.Unknown);
            Debug.Assert(location >= 0);
            Debug.Assert(sizeOrLength >= UnknownSize);
            Debug.Assert(numberOfRows >= 1 && numberOfRows <= 0x0FFFFFFF);

            Location     = location;
            SizeOrLength = sizeOrLength;
            _union       = numberOfRows | (int)jsonType << 28; // HasChildren is set to false by default
        }
Beispiel #26
0
 /// <summary>
 /// Creates a <see cref="JsonValue"/> from a JSON array.
 /// </summary>
 public JsonValue(JsonArray a)
 {
     if (a != null)
     {
         Array = a;
     }
     else
     {
         Type = JsonValueType.Null;
     }
 }
Beispiel #27
0
 /// <summary>
 /// Creates a <see cref="JsonValue"/> from a string.
 /// </summary>
 public JsonValue(string s)
 {
     if (s != null)
     {
         String = s;
     }
     else
     {
         Type = JsonValueType.Null;
     }
 }
Beispiel #28
0
 private int FindLocation(JsonValueType lookupType)
 {
     if (_reader.Index == _utf8Json.Length)
     {
         return(ForwardPass(lookupType));
     }
     else
     {
         return(BackwardPass(lookupType));
     }
 }
Beispiel #29
0
        /// <summary>
        /// Constructs a new JsonReader instance. This is a stack-only type.
        /// </summary>
        /// <param name="data">The <see cref="Span{byte}"/> value to consume. </param>
        /// <param name="encoder">An encoder used for decoding bytes from <paramref name="data"/> into characters.</param>
        public Utf8JsonReader(ReadOnlySpan <byte> data)
        {
            _reader          = default;
            _isSingleSegment = true;
            _buffer          = data;
            Depth            = 1;
            _containerMask   = 0;

            TokenType = JsonTokenType.None;
            Value     = ReadOnlySpan <byte> .Empty;
            ValueType = JsonValueType.Unknown;
        }
Beispiel #30
0
        private void AppendDbRow(JsonValueType type, int LengthOrNumberOfRows = DbRow.UnknownNumberOfRows)
        {
            while (_dbIndex >= _db.Length - DbRow.Size)
            {
                ResizeDb();
            }

            var dbRow = new DbRow(type, _reader.StartLocation, LengthOrNumberOfRows);

            MemoryMarshal.Write(_db.Slice(_dbIndex), ref dbRow);
            _dbIndex += DbRow.Size;
        }
Beispiel #31
0
 public Utf8String GetValue(JsonValueType type)
 {
     SkipEmpty();
     switch (type)
     {
         case JsonValueType.String:
             return ReadStringValue();
         case JsonValueType.Number:
             return ReadNumberValue();
         case JsonValueType.True:
             return ReadTrueValue();
         case JsonValueType.False:
             return ReadFalseValue();
         case JsonValueType.Null:
             return ReadNullValue();
         case JsonValueType.Object:
         case JsonValueType.Array:
             return Utf8String.Empty;
         default:
             throw new ArgumentException("Invalid json value type '" + type + "'.");
     }
 }
Beispiel #32
0
 public JsonNode()
 {
     m_eType = JsonValueType.JsonValueType_Null;
     m_Data = "null";
 }
Beispiel #33
0
 public JsonPrimitive(string value, JsonValueType type)
     : base(value)
 {
     Type = type;
 }
Beispiel #34
0
 JsonValue ReadByType(JsonValueType type)
 {
     JsonValue value;
     switch (type)
     {
         case JsonValueType.Array:
             value = ReadJsonArray();
             break;
         case JsonValueType.Object:
             value = ReadJsonObject();
             break;
         case JsonValueType.String:
         case JsonValueType.Error:
             value = ReadJsonElement();//try read by element
             break;
         default:
             throw new Exception("Something wrong");
     }
     return value;
 }
Beispiel #35
0
 public void SetValueType(JsonValueType type)
 {
     this.type = type;
 }
Beispiel #36
0
 public JsonNode(string aData)
 {
     m_eType = JsonValueType.JsonValueType_String;
     m_Data = aData;
 }
Beispiel #37
0
 public JsonNode(float aData)
 {
     m_eType = JsonValueType.JsonValueType_Float;
     AsFloat = aData;
 }
Beispiel #38
0
 public JsonNode(double aData)
 {
     m_eType = JsonValueType.JsonValueType_Double;
     AsDouble = aData;
 }
Beispiel #39
0
 public JsonNode(bool aData)
 {
     m_eType = JsonValueType.JsonValueType_Bool;
     AsBool = aData;
 }
Beispiel #40
0
 public JsonNode(int aData)
 {
     m_eType = JsonValueType.JsonValueType_Int;
     AsInt = aData;
 }
Beispiel #41
0
 internal static JsonSerializer CreateSerializer(Type t, JsonValueType serializeAs)
 {
     var serializableAttribute = (JsonSerializableAttribute)Attribute.GetCustomAttribute(t, typeof(JsonSerializableAttribute));
     if (serializeAs == JsonValueType.Unknown && serializableAttribute != null)
         serializeAs = serializableAttribute.SerializeAs;
     if (serializeAs == JsonValueType.Boolean || (serializeAs == JsonValueType.Unknown && t == typeof(Boolean)))
         return (serializableAttribute == null ? new JsonBooleanSerializer() : new JsonBooleanSerializer(serializableAttribute.Format));
     else if (serializeAs == JsonValueType.Number || (serializeAs == JsonValueType.Unknown && (Array.IndexOf(_numberTypes, t) >= 0 || t.IsEnum)))
         return (serializableAttribute == null ? new JsonNumberSerializer() : new JsonNumberSerializer(serializableAttribute.Format));
     else if (serializeAs == JsonValueType.String || (serializeAs == JsonValueType.Unknown && Array.IndexOf(_stringTypes, t) >= 0))
         return (serializableAttribute == null ? new JsonStringSerializer() : new JsonStringSerializer(serializableAttribute.Format));
     else if ((serializeAs == JsonValueType.Array || serializeAs == JsonValueType.Unknown) && t.GetInterface("IEnumerable`1") != null)
     {
         Type elementType;
         if (t.IsArray)
             elementType = t.GetElementType();
         else
         {
             var genericEnumerable = t.GetInterface("IEnumerable`1");
             elementType = genericEnumerable.GetGenericArguments()[0];
         }
         if (!_arraySerializers.ContainsKey(t))
         {
             var serializerType = typeof(JsonArraySerializer<,>);
             serializerType = serializerType.MakeGenericType(t, elementType);
             _arraySerializers.Add(t, (JsonSerializer)Activator.CreateInstance(serializerType));
         }
         return _arraySerializers[t];
     }
     else if (serializeAs == JsonValueType.Object || serializeAs == JsonValueType.Unknown)
     {
         if (!_serializers.ContainsKey(t))
         {
             var serializerType = typeof(JsonSerializer<>);
             serializerType = serializerType.MakeGenericType(t);
             _serializers.Add(t, (JsonSerializer)Activator.CreateInstance(serializerType));
         }
         return _serializers[t];
     }
     throw new JsonSerializationException("Unable to create serializer");
 }
Beispiel #42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="JsonSerializer"/> class.
 /// </summary>
 /// <param name="serializerType">Type of the serializer.</param>
 /// <param name="defaultFormat">The default format.</param>
 protected JsonSerializer(JsonValueType serializerType, string defaultFormat)
 {
     SerializerType = serializerType;
     DefaultFormat = defaultFormat;
 }