예제 #1
0
        private async void BroadcastMessage(Message message)
        {
            JsonElement jsonElement = (JsonElement)message.Content;

            switch (message.Type)
            {
            case MessageType.START_GAME:
                CanStartGame = jsonElement.GetBoolean();
                break;

            case MessageType.PLAYER_MOVE:
                BoardCell playerCell = (BoardCell)Enum.Parse(typeof(BoardCell), jsonElement.GetProperty("playerCell").ToString());
                int       index      = jsonElement.GetProperty("index").GetInt32();
                GameManager.ExecuteMove(playerCell, index);
                HandleGameFinish(index);
                break;

            case MessageType.DISCONNECT_GAME:
                IsInterrupted = jsonElement.GetBoolean();
                await DisconnectAsync();

                break;

            default:
                break;
            }

            StateHasChanged();
        }
예제 #2
0
        private static object ParseJson(JsonElement element)
        {
            switch (element.ValueKind)
            {
            case JsonValueKind.Number:
                return(element.GetInt32());

            case JsonValueKind.True:
            case JsonValueKind.False:
                return(element.GetBoolean());

            case JsonValueKind.String:
                return(element.GetString());

            case JsonValueKind.Array:
                var array = new List <object>();
                foreach (var item in element.EnumerateArray())
                {
                    array.Add(ParseJson(item));
                }
                return(array);

            case JsonValueKind.Object:
                var obj = new Dictionary <string, object>();
                foreach (var prop in element.EnumerateObject())
                {
                    obj.Add(prop.Name, ParseJson(prop.Value));
                }
                return(obj);

            default:
                return(null);
            }
        }
예제 #3
0
        private object GetValue(JsonElement enumValue)
        {
            switch (enumValue.ValueKind)
            {
            case JsonValueKind.String: return(enumValue.GetString());

            case JsonValueKind.Number:
                if (enumValue.TryGetInt32(out Int32 intValue))
                {
                    return(enumValue.GetInt32());
                }
                if (enumValue.TryGetInt64(out Int64 LongValue))
                {
                    return(enumValue.GetInt64());
                }
                return(enumValue.GetDouble());

            case JsonValueKind.True:
            case JsonValueKind.False:
                return(enumValue.GetBoolean());

            case JsonValueKind.Null:
                return(null);

            default:
                return(enumValue.ToString());
            }
        }
예제 #4
0
        private static object WrapResultObject(JsonElement value)
        {
            switch (value.ValueKind)
            {
            case JsonValueKind.Array:
                return(value.EnumerateArray()
                       .Select(x => WrapResultObject(x))
                       .ToList());

            case JsonValueKind.Object:
                return(new DynamicJsonObject(value));

            case JsonValueKind.False:
            case JsonValueKind.True:
                return(value.GetBoolean());

            case JsonValueKind.String:
                return(value.GetString());

            case JsonValueKind.Number:
                return(value.GetInt64());

            case JsonValueKind.Null:
            case JsonValueKind.Undefined:
                return(null);

            default:
                return(value);
            }
        }
예제 #5
0
        protected object GetValue(JsonElement elm)
        {
            object value = null;

            switch (elm.ValueKind)
            {
            case JsonValueKind.String:
                value = elm.GetString();
                break;

            case JsonValueKind.Number:
                value = elm.GetInt32();
                break;

            case JsonValueKind.True:
                value = elm.GetBoolean();
                break;

            case JsonValueKind.Array:
                var values         = new List <object>();
                var enumerateArray = elm.EnumerateArray();
                while (enumerateArray.MoveNext())
                {
                    values.Add(GetValue(enumerateArray.Current));
                }

                value = values;
                break;
            }

            return(value);
        }
        private static bool TryGetPrimitiveFromJsonElement(JsonElement jsonElement, out object elementValue)
        {
            elementValue = null;
            if (jsonElement.ValueKind == JsonValueKind.True || jsonElement.ValueKind == JsonValueKind.False)
            {
                elementValue = jsonElement.GetBoolean();
            }
            else if (jsonElement.ValueKind == JsonValueKind.Number)
            {
                if (jsonElement.TryGetInt32(out var vali))
                {
                    elementValue = vali;
                }
                if (jsonElement.TryGetInt64(out var vall))
                {
                    elementValue = vall;
                }
                if (jsonElement.TryGetDouble(out var val))
                {
                    elementValue = val;
                }
            }
            else if (jsonElement.ValueKind == JsonValueKind.String)
            {
                elementValue = jsonElement.GetString();
            }
            else if (jsonElement.ValueKind == JsonValueKind.Undefined)
            {
                elementValue = "";
            }

            return(elementValue != null);
        }
예제 #7
0
        static object GetPropertyValue(JsonElement jsonElement)
        {
            switch (jsonElement.ValueKind)
            {
            case JsonValueKind.String:
                return(jsonElement.GetString());

            case JsonValueKind.Number:
                int integerOutput;

                if (jsonElement.TryGetInt32(out integerOutput))
                {
                    return(integerOutput);
                }
                else
                {
                    return(jsonElement.GetDecimal());
                }

            case JsonValueKind.True:
            case JsonValueKind.False:
                return(jsonElement.GetBoolean());

            case JsonValueKind.Null:
                return(null);

            case JsonValueKind.Object:
            case JsonValueKind.Array:
                return(ParseJsonElement(jsonElement));
            }

            throw new ArgumentException();
        }
예제 #8
0
        private string GetStringValue(JsonElement value)
        {
            var valueKind = value.ValueKind;

            if (valueKind == JsonValueKind.Array)
            {
                return(string.Empty);
            }

            if (valueKind == JsonValueKind.False || valueKind == JsonValueKind.True)
            {
                return(value.GetBoolean().ToString());
            }

            if (valueKind == JsonValueKind.Number)
            {
                return(value.GetDecimal().ToString());
            }

            if (valueKind == JsonValueKind.String)
            {
                return(value.GetString());
            }

            return(default);
예제 #9
0
        public bool ConnectionIsValid()
        {
            if (RestDriverErrorState != RestDriverErrorState.NoError)
            {
                return(false);
            }

            try
            {
                string       rawJson      = webClient.DownloadString("/startup/validate");
                JsonDocument jsonDocument = JsonDocument.Parse(rawJson);
                JsonElement  isValid      = jsonDocument.RootElement.GetProperty("isValid");
                return(isValid.GetBoolean());
            }
            catch (WebException web)
            {
                Console.WriteLine(web.Status);
                if (web.Status == WebExceptionStatus.ProtocolError)
                {
                    HttpWebResponse hwr = (HttpWebResponse)web.Response;
                    if (hwr.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        Console.WriteLine("Die Lizenznummer \"{0}\" wurde abgelehnt.", this.license);
                    }
                    else
                    {
                        Console.WriteLine(hwr.StatusDescription);
                    }
                }
                return(false);
            }
        }
예제 #10
0
        public static void SetValueFromJson(this PropertyInfo property, Object obj, JsonElement value, string dateTimeFormat = null)
        {
            TypeCode typeCode = Type.GetTypeCode(property.PropertyType);

            switch (typeCode)
            {
            case TypeCode.Int32:
                int int32Value = value.GetInt32();
                property.SetValue(obj, int32Value);
                break;

            case TypeCode.Int64:
                long int64Value = value.GetInt64();
                property.SetValue(obj, int64Value);
                break;

            case TypeCode.Double:
                double doubleValue = value.GetDouble();
                property.SetValue(obj, doubleValue);
                break;

            case TypeCode.Decimal:
                decimal decimalValue = value.GetDecimal();
                property.SetValue(obj, decimalValue);
                break;

            case TypeCode.Boolean:
                bool boolValue = value.GetBoolean();
                property.SetValue(obj, boolValue);
                break;

            case TypeCode.DateTime:
                DateTime dateTimeValue;
                if (value.ValueKind == JsonValueKind.Null)
                {
                    dateTimeValue = DateTime.MinValue;
                }
                else if (!string.IsNullOrEmpty(dateTimeFormat))
                {
                    var stringDateTimeValue = value.GetString();
                    dateTimeValue = DateTime.ParseExact(stringDateTimeValue, dateTimeFormat, CultureInfo.InvariantCulture);
                }
                else
                {
                    dateTimeValue = value.GetDateTime();
                }

                property.SetValue(obj, dateTimeValue);
                break;

            case TypeCode.String:
                string stringValue = value.GetString();
                property.SetValue(obj, stringValue);
                break;

            default:
                //ThrowNotImplementedException(type); TODO: Сделать исключение.
                break;
            }
        }
        public static dynamic ParseValue(this JsonElement el)
        {
            switch (el.ValueKind)
            {
            case JsonValueKind.Object:
                return(el.CreateDictionary());

            case JsonValueKind.Array:
                var list = new List <dynamic>();
                foreach (var item in el.EnumerateArray())
                {
                    list.Add(item.ParseValue());
                }
                return(list.ToArray());

            case JsonValueKind.Number:
                return(el.GetDouble());

            case JsonValueKind.String:
                return(el.GetString());

            case JsonValueKind.False:
            case JsonValueKind.True:
                return(el.GetBoolean());

            case JsonValueKind.Null:
            case JsonValueKind.Undefined:
            default:
                return(null);
            }
        }
예제 #12
0
        private object GetSettingValue(string name, JsonElement jsonElement)
        {
            switch (jsonElement.ValueKind)
            {
            case JsonValueKind.Number:
                return(jsonElement.GetDouble());

            case JsonValueKind.String:
                return(jsonElement.GetString());

            case JsonValueKind.True:
            case JsonValueKind.False:
                return(jsonElement.GetBoolean());

            case JsonValueKind.Object:
                Dictionary <string, object> dict = new Dictionary <string, object>();
                foreach (var item in jsonElement.EnumerateObject())
                {
                    dict[item.Name] = GetSettingValue(name, item.Value);
                }
                return(dict);

            default:
                throw logger.Error(new SettingException(name, jsonElement, "Unsupported type"));
            }
        }
예제 #13
0
        public static object GetValue(this JsonElement json, Type type)
        {
            switch (Type.GetTypeCode(type))
            {
            case TypeCode.Boolean: return(json.GetBoolean());

            case TypeCode.SByte: return(json.GetSByte());

            case TypeCode.Int16: return(json.GetInt16());

            case TypeCode.Int32: return(json.GetInt32());

            case TypeCode.Int64: return(json.GetInt64());

            case TypeCode.Byte: return(json.GetByte());

            case TypeCode.UInt16: return(json.GetUInt16());

            case TypeCode.UInt32: return(json.GetUInt32());

            case TypeCode.UInt64: return(json.GetUInt64());

            case TypeCode.Single: return(json.GetSingle());

            case TypeCode.Double: return(json.GetDouble());

            case TypeCode.Decimal: return(json.GetDecimal());

            case TypeCode.String: return(json.GetString());

            case TypeCode.DateTime: return(json.GetDateTime());
            }
            return(Convert.ChangeType(json.GetRawText(), type));
        }
예제 #14
0
 public static bool?GetNullableBool(this JsonElement jsonElement)
 {
     if (jsonElement.ValueKind == JsonValueKind.Null)
     {
         return(null);
     }
     return(jsonElement.GetBoolean());
 }
예제 #15
0
        public static void ExpandoObject()
        {
            ExpandoObject expando = JsonSerializer.Deserialize <ExpandoObject>(Json);

            Assert.Equal(8, ((IDictionary <string, object>)expando).Keys.Count);

            dynamic obj = expando;

            VerifyPrimitives();
            VerifyObject();
            VerifyArray();

            // Re-serialize
            string json = JsonSerializer.Serialize <ExpandoObject>(obj);

            JsonTestHelper.AssertJsonEqual(Json, json);

            json = JsonSerializer.Serialize <dynamic>(obj);
            JsonTestHelper.AssertJsonEqual(Json, json);

            json = JsonSerializer.Serialize(obj);
            JsonTestHelper.AssertJsonEqual(Json, json);

            void VerifyPrimitives()
            {
                JsonElement jsonElement = obj.MyString;

                Assert.Equal("Hello", jsonElement.GetString());

                jsonElement = obj.MyBoolean;
                Assert.True(jsonElement.GetBoolean());

                jsonElement = obj.MyInt;
                Assert.Equal(42, jsonElement.GetInt32());

                jsonElement = obj.MyDateTime;
                Assert.Equal(MyDateTime, jsonElement.GetDateTime());

                jsonElement = obj.MyGuid;
                Assert.Equal(MyGuid, jsonElement.GetGuid());
            }

            void VerifyObject()
            {
                JsonElement jsonElement = obj.MyObject;

                // Here we access a property on a nested object and must use JsonElement (not a dynamic property).
                Assert.Equal("World", jsonElement.GetProperty("MyString").GetString());
            }

            void VerifyArray()
            {
                JsonElement jsonElement = obj.MyArray;

                Assert.Equal(2, jsonElement.EnumerateArray().Count());
            }
        }
예제 #16
0
        public async Task TestActorSettings()
        {
            var actorType = typeof(TestActor);

            var options = new ActorRuntimeOptions();

            options.Actors.RegisterActor <TestActor>();
            options.ActorIdleTimeout        = TimeSpan.FromSeconds(33);
            options.ActorScanInterval       = TimeSpan.FromSeconds(44);
            options.DrainOngoingCallTimeout = TimeSpan.FromSeconds(55);
            options.DrainRebalancedActors   = true;

            var runtime = new ActorRuntime(options, loggerFactory, activatorFactory, proxyFactory);

            Assert.Contains(actorType.Name, runtime.RegisteredActors.Select(a => a.Type.ActorTypeName), StringComparer.InvariantCulture);

            ArrayBufferWriter <byte> writer = new ArrayBufferWriter <byte>();
            await runtime.SerializeSettingsAndRegisteredTypes(writer);

            // read back the serialized json
            var    array = writer.WrittenSpan.ToArray();
            string s     = Encoding.UTF8.GetString(array, 0, array.Length);

            JsonDocument document = JsonDocument.Parse(s);
            JsonElement  root     = document.RootElement;

            // parse out the entities array
            JsonElement element = root.GetProperty("entities");

            Assert.Equal(1, element.GetArrayLength());

            JsonElement arrayElement = element[0];
            string      actor        = arrayElement.GetString();

            Assert.Equal("TestActor", actor);

            // validate the other properties have expected values
            element = root.GetProperty("actorIdleTimeout");
            Assert.Equal(TimeSpan.FromSeconds(33), ConverterUtils.ConvertTimeSpanFromDaprFormat(element.GetString()));

            element = root.GetProperty("actorScanInterval");
            Assert.Equal(TimeSpan.FromSeconds(44), ConverterUtils.ConvertTimeSpanFromDaprFormat(element.GetString()));

            element = root.GetProperty("drainOngoingCallTimeout");
            Assert.Equal(TimeSpan.FromSeconds(55), ConverterUtils.ConvertTimeSpanFromDaprFormat(element.GetString()));

            element = root.GetProperty("drainRebalancedActors");
            Assert.True(element.GetBoolean());

            bool found = root.TryGetProperty("remindersStoragePartitions", out element);

            Assert.False(found, "remindersStoragePartitions should not be serialized");

            JsonElement jsonValue;

            Assert.False(root.GetProperty("reentrancy").TryGetProperty("maxStackDepth", out jsonValue));
        }
예제 #17
0
        /// <summary>
        /// JsonElement の値を真偽値に変換します。
        /// </summary>
        /// <param name="prop">JsonElement。</param>
        /// <returns>真偽値に変換された JsonElement。</returns>
        public static bool ToBoolean(JsonElement prop)
        {
            if (prop.ValueKind == JsonValueKind.True || prop.ValueKind == JsonValueKind.False)
            {
                return(prop.GetBoolean());
            }

            throw new ArgumentException();
        }
예제 #18
0
        public override void SerializePrimitive <T>(ref T val)
        {
            switch (val)
            {
            case bool:
                Unsafe.As <T, bool>(ref val) = currentNode.GetBoolean();
                break;

            case int:
                Unsafe.As <T, int>(ref val) = currentNode.GetInt32();
                break;

            case uint:
                Unsafe.As <T, uint>(ref val) = currentNode.GetUInt32();
                break;

            case float:
                Unsafe.As <T, float>(ref val) = currentNode.GetSingle();
                break;

            case double:
                Unsafe.As <T, double>(ref val) = currentNode.GetDouble();
                break;

            case long:
                Unsafe.As <T, long>(ref val) = currentNode.GetInt64();
                break;

            case ulong:
                Unsafe.As <T, ulong>(ref val) = currentNode.GetUInt64();
                break;

            case short:
                Unsafe.As <T, short>(ref val) = currentNode.GetInt16();
                break;

            case ushort:
                Unsafe.As <T, ushort>(ref val) = currentNode.GetUInt16();
                break;

            case char:
                Unsafe.As <T, char>(ref val) = (char)currentNode.GetUInt16();
                break;

            case sbyte:
                Unsafe.As <T, sbyte>(ref val) = currentNode.GetSByte();
                break;

            case byte:
                Unsafe.As <T, byte>(ref val) = currentNode.GetByte();
                break;

            case decimal:
                Unsafe.As <T, decimal>(ref val) = currentNode.GetDecimal();
                break;
            }
        }
        private static bool IsMatchingType(Type type, JsonElement jsonElement, JsonSerializerOptions jsonSerializerOptions, out object value)
        {
            if (IsMatchingBoolean(type, jsonElement))
            {
                value = jsonElement.GetBoolean();
                return(true);
            }

            if (IsMatchingInteger(type, jsonElement))
            {
                value = jsonElement.GetInt32();
                return(true);
            }

            if (IsMatchingDouble(type, jsonElement))
            {
                value = jsonElement.GetDouble();
                return(true);
            }

            if (IsMatchingString(type, jsonElement))
            {
                value = jsonElement.GetString();
                return(true);
            }

            if (IsMatchingObject(type, jsonElement))
            {
                try
                {
                    value = JsonSerializer.Deserialize(jsonElement.GetRawText(), type, jsonSerializerOptions);
                    return(true);
                }
                catch (JsonException)
                {
                    // Ignore if there is an error deserializing into this object type
                }
            }

            if (IsMatchingArray(type, jsonElement))
            {
                try
                {
                    value = JsonSerializer.Deserialize(jsonElement.GetRawText(), type, jsonSerializerOptions);
                    return(true);
                }
                catch (JsonException)
                {
                    // Ignore if there is an error deserializing into this array type
                }
            }

            value = null;
            return(false);
        }
        /// <inheritdoc/>
        protected override bool TryConvert(JsonElement source, out object?result)
        {
            if (source.ValueKind != JsonValueKind.True && source.ValueKind != JsonValueKind.False)
            {
                result = null;
                return(false);
            }

            result = source.GetBoolean();
            return(true);
        }
예제 #21
0
        public static bool?ParseAsBoolean(this JsonElement element, JsonParserContext context)
        {
            if (element.ValueKind == JsonValueKind.True || element.ValueKind == JsonValueKind.False)
            {
                return(element.GetBoolean());
            }

            context.ReportError(EdmErrorCode.UnexpectedValueKind,
                                Strings.CsdlJsonParser_UnexpectedJsonValueKind(element.ValueKind, context.Path, "Boolean"));

            return(null);
        }
예제 #22
0
 public static object ToObject(this JsonElement element, ColumnType columnType)
 {
     return(columnType switch
     {
         ColumnType.Boolean => element.GetBoolean(),
         ColumnType.Decimal => element.GetDecimal(),
         ColumnType.Integer => element.GetInt64(),
         ColumnType.String => element.GetString(),
         ColumnType.DateTime => element.GetDateTime(),
         _ => throw new ArgumentException($"Unsupported columnType conversion [{columnType}]",
                                          nameof(columnType))
     });
예제 #23
0
        public void TestActorSettings()
        {
            var actorType    = typeof(TestActor);
            var actorRuntime = new ActorRuntime();

            Assert.Empty(actorRuntime.RegisteredActorTypes);

            actorRuntime.ConfigureActorSettings(a =>
            {
                a.ActorIdleTimeout        = TimeSpan.FromSeconds(33);
                a.ActorScanInterval       = TimeSpan.FromSeconds(44);
                a.DrainOngoingCallTimeout = TimeSpan.FromSeconds(55);
                a.DrainRebalancedActors   = true;
            });

            actorRuntime.RegisterActor <TestActor>();

            Assert.Contains(actorType.Name, actorRuntime.RegisteredActorTypes, StringComparer.InvariantCulture);

            ArrayBufferWriter <byte> writer = new ArrayBufferWriter <byte>();

            actorRuntime.SerializeSettingsAndRegisteredTypes(writer).GetAwaiter().GetResult();

            // read back the serialized json
            var    array = writer.WrittenSpan.ToArray();
            string s     = Encoding.UTF8.GetString(array, 0, array.Length);

            JsonDocument document = JsonDocument.Parse(s);
            JsonElement  root     = document.RootElement;

            // parse out the entities array
            JsonElement element = root.GetProperty("entities");

            Assert.Equal(1, element.GetArrayLength());

            JsonElement arrayElement = element[0];
            string      actor        = arrayElement.GetString();

            Assert.Equal("TestActor", actor);

            // validate the other properties have expected values
            element = root.GetProperty("actorIdleTimeout");
            Assert.Equal(TimeSpan.FromSeconds(33), ConverterUtils.ConvertTimeSpanFromDaprFormat(element.GetString()));

            element = root.GetProperty("actorScanInterval");
            Assert.Equal(TimeSpan.FromSeconds(44), ConverterUtils.ConvertTimeSpanFromDaprFormat(element.GetString()));

            element = root.GetProperty("drainOngoingCallTimeout");
            Assert.Equal(TimeSpan.FromSeconds(55), ConverterUtils.ConvertTimeSpanFromDaprFormat(element.GetString()));

            element = root.GetProperty("drainRebalancedActors");
            Assert.True(element.GetBoolean());
        }
예제 #24
0
        public object UpdateObj(JsonElement o, JsonElement t)
        {
            switch (t.ValueKind)
            {
            case JsonValueKind.True:
            case JsonValueKind.False:
                if (o.ValueKind == JsonValueKind.True || o.ValueKind == JsonValueKind.False)
                {
                    return(o.GetBoolean());
                }
                return(t.GetBoolean());

            case JsonValueKind.Number:
                if (o.ValueKind == JsonValueKind.Number)
                {
                    return(o.GetDouble());
                }
                return(t.GetDouble());

            case JsonValueKind.String:
                if (o.ValueKind == JsonValueKind.String)
                {
                    return(o.GetString());
                }
                return(t.GetString());

            case JsonValueKind.Null:
                return(null);

            case JsonValueKind.Object:
                Dictionary <string, object> dic = new Dictionary <string, object>();
                if (o.ValueKind == JsonValueKind.Object)
                {
                    foreach (var item in t.EnumerateObject())
                    {
                        try
                        {
                            var oprop = o.GetProperty(item.Name);
                            dic.Add(item.Name, UpdateObj(oprop, item.Value));
                        }
                        catch
                        {
                            dic.Add(item.Name, item.Value);
                        }
                    }
                }
                else
                {
                    foreach (var item in t.EnumerateObject())
                    {
                        dic.Add(item.Name, UpdateObj(default, item.Value));
                    }
                }
예제 #25
0
        private static IOpenApiAny CreateFromJsonElement(JsonElement jsonElement)
        {
            if (jsonElement.ValueKind == JsonValueKind.Null)
            {
                return(new OpenApiNull());
            }

            if (jsonElement.ValueKind == JsonValueKind.True || jsonElement.ValueKind == JsonValueKind.False)
            {
                return(new OpenApiBoolean(jsonElement.GetBoolean()));
            }

            if (jsonElement.ValueKind == JsonValueKind.Number)
            {
                if (jsonElement.TryGetInt32(out int intValue))
                {
                    return(new OpenApiInteger(intValue));
                }

                if (jsonElement.TryGetInt64(out long longValue))
                {
                    return(new OpenApiLong(longValue));
                }

                if (jsonElement.TryGetSingle(out float floatValue) && !float.IsInfinity(floatValue))
                {
                    return(new OpenApiFloat(floatValue));
                }

                if (jsonElement.TryGetDouble(out double doubleValue))
                {
                    return(new OpenApiDouble(doubleValue));
                }
            }

            if (jsonElement.ValueKind == JsonValueKind.String)
            {
                return(new OpenApiString(jsonElement.ToString()));
            }

            if (jsonElement.ValueKind == JsonValueKind.Array)
            {
                return(CreateOpenApiArray(jsonElement));
            }

            if (jsonElement.ValueKind == JsonValueKind.Object)
            {
                return(CreateOpenApiObject(jsonElement));
            }

            throw new System.ArgumentException($"Unsupported value kind {jsonElement.ValueKind}");
        }
예제 #26
0
        public static object GetValueFromJsonElement(JsonElement val)
        {
            switch (val.ValueKind)
            {
            case JsonValueKind.String:
                return(val.GetString());

            case JsonValueKind.True:
                return(val.GetBoolean());

            case JsonValueKind.False:
                return(val.GetBoolean());

            case JsonValueKind.Number:
                var oki = val.TryGetInt32(out var vali);
                if (oki)
                {
                    return(vali);
                }

                var okl = val.TryGetInt64(out var vall);
                if (okl)
                {
                    return(vall);
                }

                var okd = val.TryGetDouble(out var vald);
                if (okd)
                {
                    return(vald);
                }
                throw new Exception("Unexpected JSON value type");

            default:
                throw new Exception("Unexpected JSON value type");
            }
        }
예제 #27
0
        internal static object CastFromJsValue(object obj)
        {
#if OPENSILVER
            if (!Interop.IsRunningInTheSimulator_WorkAround)
            {
                if (obj != null && (obj is string || obj.GetType().IsPrimitive))
                {
                    return(obj);
                }

                JsonElement jsonElement = (JsonElement)obj;
                object      res;
                switch (jsonElement.ValueKind)
                {
                case JsonValueKind.Object:
                case JsonValueKind.Array:
                    res = obj;
                    break;

                case JsonValueKind.String:
                    res = jsonElement.GetString();
                    break;

                case JsonValueKind.Number:
                    res = jsonElement.GetSingle();
                    break;

                case JsonValueKind.True:
                case JsonValueKind.False:
                    res = jsonElement.GetBoolean();
                    break;

                case JsonValueKind.Undefined:
                case JsonValueKind.Null:
                    res = null;
                    break;

                default:
                    res = null;
                    break;
                }
                return(res);
            }
            else
#endif
            {
                return(DotNetForHtml5.Core.INTERNAL_Simulator.ConvertBrowserResult(obj));
            }
        }
예제 #28
0
 /// <summary>
 /// Read setting value from JSON value according to type name. JSON value will be treated as string or string array if type name cannot be recognized.
 /// </summary>
 /// <param name="jsonValue">JSON value.</param>
 /// <param name="typeName">Type name.</param>
 /// <returns>Read setting value.</returns>
 protected object ReadJsonValue(JsonElement jsonValue, string typeName)
 {
     return(typeName switch
     {
         BooleanType => jsonValue.ValueKind switch
         {
             JsonValueKind.Array => new bool[jsonValue.GetArrayLength()].Also((array) =>
             {
                 var index = 0;
                 foreach (var e in jsonValue.EnumerateArray())
                 {
                     array[index++] = (bool)this.ReadJsonValue(e, typeName);
                 }
             }),
             _ => jsonValue.GetBoolean(),
         },
예제 #29
0
        private object?SerializeJson(string ctx, JsonElement element)
        {
            switch (element.ValueKind)
            {
            case JsonValueKind.Undefined:
            case JsonValueKind.Null:
                return(null);

            case JsonValueKind.String:
                return(element.GetString());

            case JsonValueKind.Number:
                return(element.GetDouble());

            case JsonValueKind.True:
            case JsonValueKind.False:
                return(element.GetBoolean());

            case JsonValueKind.Array:
            {
                var result = ImmutableArray.CreateBuilder <object?>();
                var index  = 0;
                foreach (var child in element.EnumerateArray())
                {
                    result.Add(SerializeJson($"{ctx}[{index}]", child));
                    index++;
                }

                return(result.ToImmutable());
            }

            case JsonValueKind.Object:
            {
                var result = ImmutableDictionary.CreateBuilder <string, object?>();
                foreach (var x in element.EnumerateObject())
                {
                    result[x.Name] = SerializeJson($"{ctx}.{x.Name}", x.Value);
                }

                return(result.ToImmutable());
            }

            default:
                throw new InvalidOperationException($"Unknown {nameof(JsonElement)}.{nameof(JsonElement.ValueKind)}: {element.ValueKind}");
            }
        }
예제 #30
0
        public static void ParseUntyped()
        {
            object obj = JsonSerializer.Parse <object>(@"""hello""");

            Assert.IsType <JsonElement>(obj);
            JsonElement element = (JsonElement)obj;

            Assert.Equal(JsonValueType.String, element.Type);
            Assert.Equal("hello", element.GetString());

            obj     = JsonSerializer.Parse <object>(@"true");
            element = (JsonElement)obj;
            Assert.Equal(JsonValueType.True, element.Type);
            Assert.Equal(true, element.GetBoolean());

            obj = JsonSerializer.Parse <object>(@"null");
            Assert.Null(obj);
        }