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);
        }
        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);
        }
Example #3
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;
            }
        }
Example #4
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);
        }
        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());
        }
        //Метод для обрабокти файла с типами объектов 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);
        }
        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;
            }
        }
Example #8
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);
        }
Example #9
0
 public bool MoveNext()
 {
     return(_enumerator.MoveNext());
 }
Example #10
0
 public bool MoveNext()
 {
     return(objectEnumerator.MoveNext());
 }