Exemplo n.º 1
0
        /// <summary>
        /// Demonstration of the JsonElement
        /// </summary>
        public static async void JsonElement_Example()
        {
            JsonDocument document    = JsonDocument_ParseAsync(new JsonDocumentOptions());
            JsonElement  rootElement = document.RootElement;

            Console.WriteLine("{0}", rootElement.ValueKind); // Object

            // Get an individual property
            JsonElement element = rootElement.GetProperty("count");

            Console.WriteLine("{0}", element.ValueKind);   // Number
            Console.WriteLine("{0}", element.GetUInt32()); // 9

            element = rootElement.GetProperty("next");
            Console.WriteLine("{0} {1}", element.ValueKind, element.GetRawText()); // Null
            try
            {
                Console.WriteLine("{0}", element.GetUInt32()); // Exception
            }

            catch { Console.WriteLine("Exception as expected"); }

            // You can only get properties that are at the same level as the JsonElement
            try
            {
                element = rootElement.GetProperty("full_name");
                Console.WriteLine("{0} {1}", element.ValueKind, element.GetRawText()); // Number
            }
            catch { Console.WriteLine("Exception as expected"); }

            JsonElement elementArray = rootElement.GetProperty("results");

            Console.WriteLine("{0} {1}", elementArray.ValueKind, elementArray.GetArrayLength()); // Array

            // We cannot access an individual property of an object from an Array
            try
            {
                element = elementArray.GetProperty("full_name");
                Console.WriteLine("{0} {1}", element.ValueKind, element.GetRawText()); // Number
            }
            catch { Console.WriteLine("Exception as expected"); }

            // Grab the first element (a JSON Object) in the array using LINQ.
            element = elementArray.EnumerateArray().First();
            Console.WriteLine("{0}", element.ValueKind); // Object

            // Reference an object in the array using Item[index]
            element = elementArray[1];
            Console.WriteLine("{0} {1}", element.ValueKind, element.GetRawText()); // Object

            // Access a property of the object.
            Console.WriteLine("{0} {1}", element.GetProperty("full_name").ValueKind, element.GetProperty("full_name").GetRawText()); // Number

            JsonElement.ObjectEnumerator objectEnumerator = rootElement.EnumerateObject();
            foreach (JsonProperty property in objectEnumerator)
            {
                //Console.WriteLine("Element: {0}: {1}", property.Name, property.Value);
            }
            //Console.WriteLine("Item[0] {0}", rootElement);
        }
        public async Task <List <AccountModel> > getAccounts(string username)
        {
            string endpoint = "/account-table/.json";

            HttpClient          client = new HttpClient();
            HttpResponseMessage resp   = await client.GetAsync(databaseURI + endpoint);

            Stream jsonStream = await resp.Content.ReadAsStreamAsync();

            JsonDocument jsonDoc = await JsonDocument.ParseAsync(jsonStream);

            JsonElement.ObjectEnumerator jsonEnum = jsonDoc.RootElement.EnumerateObject();

            List <AccountModel> models = new List <AccountModel>();

            while (jsonEnum.MoveNext())
            {
                string       nestedJson = jsonEnum.Current.Value.GetRawText();
                AccountModel model      = JsonSerializer.Deserialize <AccountModel>(nestedJson);

                models.Add(model);
            }

            return(models);
        }
Exemplo n.º 3
0
        public void Verify()
        {
            Assert.IsType <JsonElement>(Array);
            ValidateArray((JsonElement)Array);
            Assert.IsType <JsonElement>(Object);
            JsonElement jsonObject = (JsonElement)Object;

            Assert.Equal(JsonValueKind.Object, jsonObject.ValueKind);
            JsonElement.ObjectEnumerator enumerator = jsonObject.EnumerateObject();
            JsonProperty property = enumerator.First();

            Assert.Equal("NestedArray", property.Name);
            Assert.True(property.NameEquals("NestedArray"));
            ValidateArray(property.Value);

            void ValidateArray(JsonElement element)
            {
                Assert.Equal(JsonValueKind.Array, element.ValueKind);
                JsonElement[] elements = element.EnumerateArray().ToArray();

                Assert.Equal(JsonValueKind.Number, elements[0].ValueKind);
                Assert.Equal("1", elements[0].ToString());
                Assert.Equal(JsonValueKind.String, elements[1].ValueKind);
                Assert.Equal("Hello", elements[1].ToString());
                Assert.Equal(JsonValueKind.True, elements[2].ValueKind);
                Assert.True(elements[2].GetBoolean());
                Assert.Equal(JsonValueKind.False, elements[3].ValueKind);
                Assert.False(elements[3].GetBoolean());
            }
        }
        public async Task <List <GoonModel> > getGoons()
        {
            string endpoint = "/goon-table/.json";

            HttpClient          client   = new HttpClient();
            HttpResponseMessage response = await client.GetAsync(databaseURI + endpoint);

            Stream jsonStream = await response.Content.ReadAsStreamAsync();

            JsonDocument jsonDoc = await JsonDocument.ParseAsync(jsonStream);

            JsonElement.ObjectEnumerator jsonEnumerator = jsonDoc.RootElement.EnumerateObject();

            List <GoonModel> models = new List <GoonModel>();

            while (jsonEnumerator.MoveNext())
            {
                string nestedJson = jsonEnumerator.Current.Value.GetRawText();
                Console.WriteLine(nestedJson);
                GoonModel model = JsonSerializer.Deserialize <GoonModel>(nestedJson);
                models.Add(model);
            }

            return(models);
        }
Exemplo n.º 5
0
        private static string TryGetValue(this JsonElement.ObjectEnumerator target, string propertyName)
        {
            var ret      = string.Empty;
            var property = target.FirstOrDefault(t => t.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase));

            ret = property.Value.ToString();
            return(ret);
        }
Exemplo n.º 6
0
        protected void AssertJsonObject(JsonElement.ObjectEnumerator expected, object actual)
        {
            var type = actual.GetType();

            if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(ReadOnlyDictionary <,>) || type.GetGenericTypeDefinition() == typeof(Dictionary <,>)))
            {
                // Dictionary
                var keyType = type.GetGenericArguments()[0];
                var dic     = (dynamic)actual;
                foreach (var kvp in expected)
                {
                    dynamic key;
                    if (keyType == typeof(string))
                    {
                        key = kvp.Name;
                    }
                    else
                    {
                        string keyString = string.Concat(kvp.Name.Split('_').Select(s => string.Concat(
                                                                                        s[0].ToString().ToUpper(),
                                                                                        s.Substring(1))));
                        key = Convert.ChangeType(keyString, keyType);
                        if (key == null)
                        {
                            throw new InvalidOperationException($"Expected property '{keyString}' to exist in type {type.FullName}");
                        }
                    }
                    var actualValue = dic[key];
                    this.AssertJsonObject(kvp.Value, actualValue);
                }
            }
            else
            {
                // Specific object
                foreach (var kvp in expected)
                {
                    // Try matching with JsonPropertyNameAttribute first
                    var property = type.GetProperties()
                                   .FirstOrDefault(x => x.GetCustomAttribute <JsonPropertyNameAttribute>()?.Name == kvp.Name);
                    if (property == null)
                    {
                        // Try auto matching based on name
                        string key = string.Concat(kvp.Name.Split('_').Select(s => string.Concat(
                                                                                  s[0].ToString().ToUpper(),
                                                                                  s.Substring(1))));
                        property = type.GetProperty(key);
                        if (property == null)
                        {
                            throw new InvalidOperationException($"Expected property '{key}' to exist in type {type.FullName}");
                        }
                    }

                    var actualValue = property.GetValue(actual);
                    this.AssertJsonObject(kvp.Value, actualValue);
                }
            }
        }
Exemplo n.º 7
0
        private Dictionary <string, int> ToDictionary(JsonElement.ObjectEnumerator objectEnumerator)
        {
            var d = new Dictionary <string, int>();

            foreach (var entry in objectEnumerator)
            {
                d[entry.Name] = entry.Value.GetInt32();
            }
            return(d);
        }
Exemplo n.º 8
0
        static void EnumerateEle(JsonElement ele, string indentation)
        {
            switch (ele.ValueKind)
            {
            case JsonValueKind.Object:
                JsonElement.ObjectEnumerator objEnum = ele.EnumerateObject();
                while (objEnum.MoveNext())
                {
                    JsonProperty prop      = objEnum.Current;
                    string       propName  = prop.Name;
                    JsonElement  propValue = prop.Value;
                    switch (propValue.ValueKind)
                    {
                    case JsonValueKind.Object:
                        EnumerateEle(propValue, indentation + "  ");
                        break;

                    case JsonValueKind.Array:
                        Console.WriteLine(indentation + $"{propName} is an array of length {propValue.GetArrayLength()}");
                        EnumerateEle(propValue, indentation + "      ");
                        break;

                    default:
                        Console.WriteLine(indentation + $"{propName}: {propValue}");
                        break;
                    }
                }
                break;

            case JsonValueKind.Array:
                JsonElement.ArrayEnumerator arrEnum = ele.EnumerateArray();
                int i = 1;
                while (arrEnum.MoveNext())
                {
                    Console.WriteLine(indentation + $"Item {i} of {ele.GetArrayLength()}");
                    EnumerateEle(arrEnum.Current, indentation + "  ");
                    Console.WriteLine();
                    i++;
                }
                break;

            default:
                Console.WriteLine(indentation + ele);
                break;
            }
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            string       jsonString = File.ReadAllText("Input/input.json");
            JsonDocument document   = JsonDocument.Parse(jsonString);
            var          _object    = JsonSerializer.Deserialize <JsonElement>(jsonString);

            JsonElement.ObjectEnumerator ttst = _object.EnumerateObject();
            using (var workbook = new XLWorkbook())
            {
                var worksheet = workbook.Worksheets.Add("Sheet 1");
                var column    = 1;
                var row       = 1;
                var column2   = 1;
                foreach (var item in ttst)
                {
                    if (item.Value.ValueKind.ToString() != "Array")
                    {
                        worksheet.Column(column).Cell(row).Value     = item.Name;
                        worksheet.Column(column).Cell(row + 1).Value = item.Value;
                    }
                    else
                    {
                        column2 = column;
                        string firstCell = Convert.ToChar(column + 64).ToString();
                        string lastCell  = Convert.ToChar(column + item.Value.GetArrayLength() + 63).ToString();
                        string rango     = firstCell + "1:" + lastCell + "1";
                        worksheet.Range(rango).Merge();
                        worksheet.Column(column).Cell(row).Value = item.Name;
                        var test = item.Value.EnumerateArray();
                        foreach (var subitem in test)
                        {
                            worksheet.Column(column2).Cell(row + 1).Value = subitem.ToString();
                            column2++;
                        }
                    }
                    column++;
                    row = row + 2;
                }
                workbook.SaveAs("OutPut/Test.xlsx");
            }
            Console.WriteLine(_object.GetRawText());
            Console.Write(_object);
        }
Exemplo n.º 10
0
        public async Task <IActionResult> PatchUser(int id, [FromBody] JsonElement payload)
        {
            if (payload.ValueKind == JsonValueKind.Object)
            {
                JsonElement.ObjectEnumerator enumerator = payload.EnumerateObject(); // Calling it twice does not work
                if (enumerator.Count() > 0)
                {
                    User user = await db.Users.FirstOrDefaultAsync(p => p.Id == id);

                    if (user == null)
                    {
                        return(NotFound());
                    }

                    foreach (JsonProperty prop in enumerator)
                    {
                        if (prop.Name == "name")
                        {
                            user.Name = prop.Value.GetString();
                        }
                        if (prop.Name == "email")
                        {
                            user.Email = prop.Value.GetString();
                        }
                        if (prop.Name == "password")
                        {
                            user.Password = prop.Value.GetString();
                        }
                    }

                    await db.SaveChangesAsync();

                    return(Ok(mapper.Map <UserReadDTO>(user)));
                }
            }

            return(BadRequest());
        }
Exemplo n.º 11
0
        /// <summary>
        /// 将 Form Body 中的 json 数据读取为字典(不支持对象嵌套).
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="ValueConvert"></param>
        /// <returns></returns>
        public static async Task <Dictionary <string, object> > ReadJsonBodyToDictionary(this Controller controller, Func <string, JsonElement, object> ValueConvert)
        {
            if (ValueConvert == null)
            {
                throw new ArgumentNullException(nameof(ValueConvert));
            }
            List <string> mimeTypes   = new List <string>();
            string        bodyContent = await controller.ReadBodyStringAsync(mimeTypes);

            bool is_json = mimeTypes.Contains("application/json");

            if (!is_json)
            {
                is_json = mimeTypes.Contains("text/json");
            }
            if (!is_json)
            {
                throw new Exception("不正确的请求类型 Content-Type ,应为 application/json 或 text/json");
            }

            Dictionary <string, object> data = new Dictionary <string, object>();
            JsonDocument json = JsonDocument.Parse(bodyContent);

            JsonElement.ObjectEnumerator enumerator = json.RootElement.EnumerateObject();
            object elemValue = null;

            while (enumerator.MoveNext())
            {
                elemValue = ValueConvert(enumerator.Current.Name, enumerator.Current.Value);
                if (elemValue == null)
                {
                    continue;
                }
                data.Add(enumerator.Current.Name, elemValue);
            }
            return(data);
        }
Exemplo n.º 12
0
        private RpcRequestParseResult ParseResult(JsonElement.ObjectEnumerator objectEnumerator)
        {
            RpcId         id         = default;
            string?       method     = null;
            RpcParameters?parameters = null;
            string?       rpcVersion = null;

            try
            {
                foreach (JsonProperty property in objectEnumerator)
                {
                    switch (property.Name)
                    {
                    case JsonRpcContants.IdPropertyName:
                        switch (property.Value.ValueKind)
                        {
                        case JsonValueKind.String:
                            id = new RpcId(property.Value.GetString());
                            break;

                        case JsonValueKind.Number:
                            if (!property.Value.TryGetInt64(out long longId))
                            {
                                var idError = new RpcError(RpcErrorCode.ParseError, "Unable to parse rpc id as an integer");
                                return(RpcRequestParseResult.Fail(id, idError));
                            }
                            id = new RpcId(longId);
                            break;

                        default:
                            var error = new RpcError(RpcErrorCode.ParseError, "Unable to parse rpc id as a string or an integer");
                            return(RpcRequestParseResult.Fail(id, error));
                        }
                        break;

                    case JsonRpcContants.VersionPropertyName:
                        rpcVersion = property.Value.GetString();
                        break;

                    case JsonRpcContants.MethodPropertyName:
                        method = property.Value.GetString();
                        break;

                    case JsonRpcContants.ParamsPropertyName:
                        RpcParameters ps;
                        switch (property.Value.ValueKind)
                        {
                        case JsonValueKind.Array:
                            IRpcParameter[] items = property.Value
                                                    .EnumerateArray()
                                                    .Select(this.GetParameter)
                                                    .Cast <IRpcParameter>()
                                                    .ToArray();
                            //TODO array vs list?
                            ps = new RpcParameters(items);
                            break;

                        case JsonValueKind.Object:
                            Dictionary <string, IRpcParameter> dict = property.Value
                                                                      .EnumerateObject()
                                                                      .ToDictionary(j => j.Name, j => (IRpcParameter)this.GetParameter(j.Value));
                            ps = new RpcParameters(dict);
                            break;

                        default:
                            return(RpcRequestParseResult.Fail(id, new RpcError(RpcErrorCode.InvalidRequest, "The request parameter format is invalid.")));
                        }
                        parameters = ps;
                        break;
                    }
                }

                if (string.IsNullOrWhiteSpace(method))
                {
                    return(RpcRequestParseResult.Fail(id, new RpcError(RpcErrorCode.InvalidRequest, "The request method is required.")));
                }
                if (string.IsNullOrWhiteSpace(rpcVersion))
                {
                    return(RpcRequestParseResult.Fail(id, new RpcError(RpcErrorCode.InvalidRequest, "The jsonrpc version must be specified.")));
                }
                if (!string.Equals(rpcVersion, "2.0", StringComparison.OrdinalIgnoreCase))
                {
                    return(RpcRequestParseResult.Fail(id, new RpcError(RpcErrorCode.InvalidRequest, $"The jsonrpc version '{rpcVersion}' is not supported. Supported versions: '2.0'")));
                }

                return(RpcRequestParseResult.Success(id, method !, parameters));
            }
            catch (Exception ex)
            {
                RpcError error;
                if (ex is RpcException rpcException)
                {
                    error = rpcException.ToRpcError(this.serverConfig.Value.ShowServerExceptions);
                }
                else
                {
                    error = new RpcError(RpcErrorCode.ParseError, "Failed to parse request.", ex);
                }
                return(RpcRequestParseResult.Fail(id, error));
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Jsons the equal.
        /// </summary>
        /// <param name="expected">The expected.</param>
        /// <param name="actual">The actual.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        /// <exception cref="NotSupportedException">Unexpected JsonValueKind: {valueKind}.</exception>
        private static bool JsonEqual([NotNull] JsonElement expected, [NotNull] JsonElement actual)
        {
            JsonValueKind valueKind = expected.ValueKind;

            if (valueKind != actual.ValueKind)
            {
                return(false);
            }

            switch (valueKind)
            {
            case JsonValueKind.Object:
                var propertyNames = new HashSet <string>();

                using (JsonElement.ObjectEnumerator expectedEnumerator = expected.EnumerateObject())
                {
                    foreach (JsonProperty property in expectedEnumerator)
                    {
                        _ = propertyNames.Add(property.Name);
                    }
                }

                using (JsonElement.ObjectEnumerator actualEnumerator = actual.EnumerateObject())
                {
                    foreach (JsonProperty property in actualEnumerator)
                    {
                        _ = propertyNames.Add(property.Name);
                    }
                }

                foreach (var name in propertyNames)
                {
                    if (!JsonEqual(expected.GetProperty(name), actual.GetProperty(name)))
                    {
                        return(false);
                    }
                }

                return(true);

            case JsonValueKind.Array:
                using (JsonElement.ArrayEnumerator expectedEnumerator = actual.EnumerateArray())
                {
                    using JsonElement.ArrayEnumerator actualEnumerator = expected.EnumerateArray();

                    while (expectedEnumerator.MoveNext())
                    {
                        if (!actualEnumerator.MoveNext())
                        {
                            return(false);
                        }

                        if (!JsonEqual(expectedEnumerator.Current, actualEnumerator.Current))
                        {
                            return(false);
                        }
                    }

                    return(!actualEnumerator.MoveNext());
                }

            case JsonValueKind.String:
                return(string.Equals(expected.GetString(), actual.GetString(), StringComparison.Ordinal));

            case JsonValueKind.Number:
            case JsonValueKind.True:
            case JsonValueKind.False:
            case JsonValueKind.Null:
                return(string.Equals(expected.GetRawText(), actual.GetRawText(), StringComparison.Ordinal));

            default:
                throw new NotSupportedException($"Unexpected JsonValueKind: {valueKind}.");
            }
        }
 private static JsonElement GetPropertyValue(JsonElement.ObjectEnumerator properties, string propertyName)
 {
     return(properties.FirstOrDefault(x => x.Name.Equals(propertyName)).Value);
 }
        //Метод для обрабокти файла с типами объектов TypeInfos
        public bool readFile_TypeInfos()
        {
            //откроем диалог для выбора необходимого файла
            OpenFileDialog opfd = new OpenFileDialog();

            opfd.Filter = "Файлы JSON (*.json)|*.json";

            if (opfd.ShowDialog(mainForm) == DialogResult.OK)
            {
                //объявим документ JSON с которым будем работать
                JsonDocument jsonDoc;

                try
                {
                    //откроем поток из файла JSON указанного в диалоге
                    using (FileStream fs = File.OpenRead(opfd.FileName))
                    {
                        //ловим исключения, но не будем расшифровывать
                        //усливимся, если что-то пошло не так, значит файл не годится

                        //инициализируем документ функцией парсинга потока файла
                        jsonDoc = JsonDocument.Parse(fs);
                        //возьмем корневой элемент структуры нашего JSON файла
                        JsonElement root = jsonDoc.RootElement;

                        //Первый элемент в файле JSON для данной задачи должен начинаться с Объекта
                        //Удостоверимся в этом, иначе файл считается неверного формата
                        if (root.ValueKind != JsonValueKind.Object)
                        {
                            //поставим флаг о том что считывание завершилось неудачей
                            return(false);
                        }

                        //берем перечислитель и идем далее
                        JsonElement.ObjectEnumerator obEn = root.EnumerateObject();
                        obEn.MoveNext();

                        //проверим, что название класса соответсвует структуре данного JSON документа
                        if (obEn.Current.Name != "TypeInfos")
                        {
                            //поставим флаг о том что считывание завершилось неудачей
                            return(false);
                        }

                        //Получим значения внутри объекта TypeInfos
                        var groupsTags = obEn.Current.Value;

                        //проверим что следующий элемент в файле JSON - массив
                        //в этом массиве содержится требуемое описание типов тегов
                        if (groupsTags.ValueKind != JsonValueKind.Array)
                        {
                            //поставим флаг о том что считывание завершилось неудачей
                            return(false);
                        }
                        else
                        {
                            //Инициализируем массив с тегами
                            arrTagType = new List <TagType>();


                            for (int i = 0; i < groupsTags.GetArrayLength(); i++)
                            {
                                JsonElement theGroup = groupsTags[i];
                                JsonElement.ObjectEnumerator obE_TypeName_and_Properties = theGroup.EnumerateObject();

                                //Первый шаг - Имя
                                obE_TypeName_and_Properties.MoveNext();

                                var nameVar1             = obE_TypeName_and_Properties.Current.Name;
                                var value_TargetNameType = obE_TypeName_and_Properties.Current.Value;

                                //на этом этапе мы можем получить имя "целевого типа объекта из файла"
                                //инициализируем врмененный TagType с названием TypeName
                                var tempTagType = new TagType(value_TargetNameType.ToString());



                                //Второй шаг - Свойства
                                obE_TypeName_and_Properties.MoveNext();

                                //получим значние следующего поля и получим его перечислитель
                                var propertiesInfo = obE_TypeName_and_Properties.Current.Value;
                                JsonElement.ObjectEnumerator obE_PropertiesInfo = propertiesInfo.EnumerateObject();

                                //Первый шаг для свойств
                                bool hasNext = obE_PropertiesInfo.MoveNext();

                                //пробежимся по коллекции свойств
                                while (hasNext)
                                {
                                    string tagName = obE_PropertiesInfo.Current.Name;
                                    string tagType = obE_PropertiesInfo.Current.Value.ToString();

                                    //каждое новое свойство поместим во временный tempTagType
                                    tempTagType.addPropertiesTag(tagName, tagType);

                                    hasNext = obE_PropertiesInfo.MoveNext();
                                }

                                //Добавим элемент в массив TagType
                                arrTagType.Add(tempTagType);
                            }
                        }
                    }
                }
                catch
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 16
0
        public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            switch (reader.TokenType)
            {
            case JsonTokenType.String:
                return(reader.GetString());

            case JsonTokenType.StartObject:
                using (var jsonDocument = JsonDocument.ParseValue(ref reader))
                {
                    JsonElement.ObjectEnumerator objectEnumerator = jsonDocument.RootElement.EnumerateObject();
                    IDictionary <string, Type>   types            = new Dictionary <string, Type>();
                    foreach (var obj in objectEnumerator)
                    {
                        types.Add(obj.Name, MapValueKind(obj.Value));
                    }

                    return(JsonSerializer.Deserialize
                           (
                               jsonDocument.RootElement.GetRawText(),
                               AnonymousTypeFactory.CreateAnonymousType(types)
                           ));

                    Type MapValueKind(JsonElement jsonElement)
                    {
                        switch (jsonElement.ValueKind)
                        {
                        case JsonValueKind.Undefined:
                        case JsonValueKind.Object:
                        case JsonValueKind.Array:
                            return(typeof(object));

                        case JsonValueKind.String:
                            return(typeof(string));

                        case JsonValueKind.Number:
                            if (jsonElement.TryGetByte(out byte _))
                            {
                                return(typeof(byte));
                            }
                            else if (jsonElement.TryGetInt16(out short _))
                            {
                                return(typeof(short));
                            }
                            else if (jsonElement.TryGetInt32(out int _))
                            {
                                return(typeof(int));
                            }
                            else if (jsonElement.TryGetInt64(out long _))
                            {
                                return(typeof(long));
                            }
                            else if (jsonElement.TryGetSingle(out float _))
                            {
                                return(typeof(float));
                            }
                            else if (jsonElement.TryGetDecimal(out decimal _))
                            {
                                return(typeof(decimal));
                            }
                            else if (jsonElement.TryGetDouble(out double _))
                            {
                                return(typeof(double));
                            }

                            return(typeof(double));

                        case JsonValueKind.True:
                        case JsonValueKind.False:
                            return(typeof(bool));

                        case JsonValueKind.Null:
                        default:
                            return(typeof(object));
                        }
                    }
                }

            case JsonTokenType.None:
            case JsonTokenType.EndObject:
            case JsonTokenType.StartArray:
            case JsonTokenType.EndArray:
            case JsonTokenType.PropertyName:
            case JsonTokenType.Comment:
                throw new JsonException();

            case JsonTokenType.Number:
                if (reader.TryGetByte(out byte byteValue))
                {
                    return(byteValue);
                }
                else if (reader.TryGetInt16(out short shortValue))
                {
                    return(shortValue);
                }
                else if (reader.TryGetInt32(out int intValue))
                {
                    return(intValue);
                }
                else if (reader.TryGetInt64(out long longValue))
                {
                    return(longValue);
                }
                else if (reader.TryGetSingle(out float floatValue))
                {
                    return(floatValue);
                }
                else if (reader.TryGetDecimal(out decimal decimalValue))
                {
                    return(decimalValue);
                }
                else if (reader.TryGetDouble(out double doubleValue))
                {
                    return(doubleValue);
                }

                return(0);

            case JsonTokenType.True:
                return(true);

            case JsonTokenType.False:
                return(false);

            case JsonTokenType.Null:
                return(null);
            }
            return(null);
        }
Exemplo n.º 17
0
        private void BindConfigObject(DynamicObjectExt configObj, JsonElement element, string key = null)
        {
            if (configObj == null)
            {
                return;
            }

            switch (element.ValueKind)
            {
            case JsonValueKind.Object:
                if (!string.IsNullOrWhiteSpace(key))
                {
                    DynamicObjectExt subConfigObj = new DynamicObjectExt();
                    BindConfigObject(subConfigObj, element);
                    configObj.TrySetValue(key, subConfigObj);
                }
                else
                {
                    JsonElement.ObjectEnumerator oe = element.EnumerateObject();
                    while (oe.MoveNext())
                    {
                        BindConfigObject(configObj, oe.Current.Value, oe.Current.Name);
                    }
                }
                break;

            case JsonValueKind.Array:
                if (!string.IsNullOrWhiteSpace(key))
                {
                    List <object> _list = new List <object>();

                    JsonElement.ArrayEnumerator ae = element.EnumerateArray();
                    while (ae.MoveNext())
                    {
                        switch (ae.Current.ValueKind)
                        {
                        case JsonValueKind.String:
                            _list.Add(ae.Current.GetString());
                            break;

                        case JsonValueKind.Number:
                            long value;
                            if (ae.Current.TryGetInt64(out value))
                            {
                                if (value > Int32.MaxValue)
                                {
                                    _list.Add(value);
                                }
                                else if (value > Int16.MaxValue)
                                {
                                    _list.Add((Int32)value);
                                }
                                else
                                {
                                    _list.Add((Int16)value);
                                }
                            }
                            else
                            {
                                _list.Add(ae.Current.GetDouble());
                            }
                            break;

                        case JsonValueKind.True:
                        case JsonValueKind.False:
                            _list.Add(ae.Current.GetBoolean());
                            break;

                        case JsonValueKind.Null:
                            _list.Add(null);
                            break;

                        case JsonValueKind.Object:
                        case JsonValueKind.Array:
                            DynamicObjectExt itemObj = new DynamicObjectExt();
                            BindConfigObject(itemObj, ae.Current);
                            _list.Add(itemObj);
                            break;
                        }
                    }

                    configObj.TrySetValue(key, _list);
                }
                break;

            case JsonValueKind.String:
                if (!string.IsNullOrWhiteSpace(key))
                {
                    configObj.TrySetValue(key, element.GetString());
                }
                break;

            case JsonValueKind.Number:
                if (!string.IsNullOrWhiteSpace(key))
                {
                    long value;
                    if (element.TryGetInt64(out value))
                    {
                        if (value > Int32.MaxValue)
                        {
                            configObj.TrySetValue(key, value);
                        }
                        else if (value > Int16.MaxValue)
                        {
                            configObj.TrySetValue(key, (Int32)value);
                        }
                        else
                        {
                            configObj.TrySetValue(key, (Int16)value);
                        }
                    }
                    else
                    {
                        configObj.TrySetValue(key, element.GetDouble());
                    }
                }
                break;

            case JsonValueKind.True:
            case JsonValueKind.False:
                if (!string.IsNullOrWhiteSpace(key))
                {
                    configObj.TrySetValue(key, element.GetBoolean());
                }
                break;

            case JsonValueKind.Null:
                if (!string.IsNullOrWhiteSpace(key))
                {
                    configObj.TrySetValue(key, null);
                }
                break;
            }
        }
Exemplo n.º 18
0
 public ObjectEnumerator(JsonElement.ObjectEnumerator enumerator)
 {
     _enumerator = enumerator;
 }
Exemplo n.º 19
0
        public static Dictionary <string, dynamic> parseStagePart(dynamic staticStagePart)
        {
            dynamic stagePart = staticStagePart;

            var gearDyeSlot        = 0;
            var usePrimaryColor    = true;
            var useInvestmentDecal = false;

            switch (stagePart.GetProperty("gear_dye_change_color_index").GetInt32())
            {
            case 0:
                gearDyeSlot = 0;
                break;

            case 1:
                gearDyeSlot     = 1;
                usePrimaryColor = false;
                break;

            case 2:
                gearDyeSlot = 2;
                break;

            case 3:
                gearDyeSlot     = 3;
                usePrimaryColor = false;
                break;

            case 4:
                gearDyeSlot = 4;
                break;

            case 5:
                gearDyeSlot     = 5;
                usePrimaryColor = false;
                break;

            case 6:
                gearDyeSlot        = 6;
                useInvestmentDecal = true;
                break;

            case 7:
                gearDyeSlot        = 7;
                useInvestmentDecal = true;
                break;

            default:
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("UnknownDyeChangeColorIndex[" + stagePart.GetProperty("gear_dye_change_color_index") + "]", stagePart);
                Console.ResetColor();
                break;
            }

            dynamic part = new Dictionary <string, dynamic>();

            //externalIdentifier: stagePart.external_identifier,
            //changeColorIndex: stagePart.gear_dye_change_color_index,
            //primitiveType: stagePart.primitive_type,
            //lodCategory: stagePart.lod_category,
            part.Add("gearDyeSlot", gearDyeSlot);
            part.Add("usePrimaryColor", usePrimaryColor);
            part.Add("useInvestmentDecal", useInvestmentDecal);
            //indexMin: stagePart.index_min,
            //indexMax: stagePart.index_max,
            //indexStart: stagePart.start_index,
            //indexCount: stagePart.index_count

            //foreach (var keyP in stagePart) {
            JsonElement.ObjectEnumerator stageProps = stagePart.EnumerateObject();
            while (stageProps.MoveNext())
            {
                var     keyP    = stageProps.Current;
                var     key     = keyP.Name;
                var     partKey = key;
                dynamic value   = keyP.Value;              //stagePart.GetValue(key);
                switch (key)
                {
                //case 'external_identifier': partKey = 'externalIdentifier'; break;
                case "gear_dye_change_color_index": partKey = "changeColorIndex"; break;
                //case 'primitive_type': partKey = 'primitiveType'; break;
                //case 'lod_category': partKey = 'lodCategory'; break;

                //case 'index_min': partKey = 'indexMin'; break;
                //case 'index_max': partKey = 'indexMax'; break;
                case "start_index": partKey = "indexStart"; break;
                //case 'index_count': partKey = 'indexCount'; break;

                case "shader":
                    bool hasStaticTextures = value.TryGetProperty("static_textures", out JsonElement staticTextures);
                    var  valueType         = value.GetProperty("type");
                    value      = new ExpandoObject();
                    value.type = valueType;
                    if (hasStaticTextures)
                    {
                        value.staticTextures = staticTextures;
                    }
                    break;

                //case 'static_textures': partKey = 'staticTextures'; break;

                default:
                    string[] keyWords = key.Split("_");
                    partKey = "";
                    for (var i = 0; i < keyWords.Length; i++)
                    {
                        var keyWord = keyWords[i];
                        partKey += i == 0 ? keyWord : keyWord.Substring(0, 1).ToUpper() + keyWord.Substring(1);
                    }
                    break;
                }
                part[partKey] = value;
            }

            return(part);
        }
Exemplo n.º 20
0
        public static void TestAsJsonElement()
        {
            var jsonObject = new JsonObject
            {
                { "text", "property value" },
                { "boolean", true },
                { "number", 15 },
                { "null node", (JsonNode)null },
                { "array", new JsonArray {
                      "value1", "value2"
                  } }
            };

            JsonElement jsonElement = jsonObject.AsJsonElement();

            Assert.False(jsonElement.IsImmutable);

            JsonElement.ObjectEnumerator enumerator = jsonElement.EnumerateObject();

            enumerator.MoveNext();
            Assert.Equal("text", enumerator.Current.Name);
            Assert.Equal(JsonValueKind.String, enumerator.Current.Value.ValueKind);
            Assert.Equal("property value", enumerator.Current.Value.GetString());

            enumerator.MoveNext();
            Assert.Equal("boolean", enumerator.Current.Name);
            Assert.Equal(JsonValueKind.True, enumerator.Current.Value.ValueKind);
            Assert.True(enumerator.Current.Value.GetBoolean());

            enumerator.MoveNext();
            Assert.Equal("number", enumerator.Current.Name);
            Assert.Equal(15, enumerator.Current.Value.GetInt32());
            Assert.Equal(JsonValueKind.Number, enumerator.Current.Value.ValueKind);

            enumerator.MoveNext();
            Assert.Equal("null node", enumerator.Current.Name);
            Assert.Equal(JsonValueKind.Null, enumerator.Current.Value.ValueKind);

            enumerator.MoveNext();
            Assert.Equal("array", enumerator.Current.Name);
            Assert.Equal(2, enumerator.Current.Value.GetArrayLength());
            Assert.Equal(JsonValueKind.Array, enumerator.Current.Value.ValueKind);
            JsonElement.ArrayEnumerator innerEnumerator = enumerator.Current.Value.EnumerateArray();

            innerEnumerator.MoveNext();
            Assert.Equal(JsonValueKind.String, innerEnumerator.Current.ValueKind);
            Assert.Equal("value1", innerEnumerator.Current.GetString());

            innerEnumerator.MoveNext();
            Assert.Equal(JsonValueKind.String, innerEnumerator.Current.ValueKind);
            Assert.Equal("value2", innerEnumerator.Current.GetString());

            Assert.False(innerEnumerator.MoveNext());
            innerEnumerator.Dispose();

            Assert.False(enumerator.MoveNext());
            enumerator.Dispose();

            // Modifying JsonObject will change JsonElement:

            jsonObject["text"] = new JsonNumber("123");
            Assert.Equal(123, jsonElement.GetProperty("text").GetInt32());
        }
Exemplo n.º 21
0
 public KeyValueEnumerator(JsonElement.ObjectEnumerator objectEnumerator)
 {
     this.objectEnumerator = objectEnumerator;
 }