Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > .NET Frameworks (точка нет фреймворки) > C# (си шарп)
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 27.02.2016, 00:18   #1
Delegat
 
Регистрация: 16.04.2009
Сообщений: 9
По умолчанию Конвертирование JSON строки в объект

Добрый день. Имеется JSON строка следующего вида:

Цитата:

{"status": "success", "countries": {"BD": {"count": 2, "country": "Bangladesh"}, "BE": {"count": 124, "country": "Belgium"}, "FR": {"count": 761, "country": "France"}, "BG": {"count": 30, "country": "Bulgaria"}, "MA": {"count": 3, "country": "Morocco"}, "TR": {"count": 67, "country": "Turkey"}, "BN": {"count": 1, "country": "Brunei Darussalam"}, "BO": {"count": 3, "country": "Bolivia, Plurination"}, "JP": {"count": 2995, "country": "Japan"}, "BR": {"count": 78, "country": "Brazil"}, "BS": {"count": 1, "country": "Bahamas"}, "JE": {"count": 3, "country": "Jersey"}, "BY": {"count": 3, "country": "Belarus"}, "FO": {"count": 26, "country": "Faroe Islands"}, "RU": {"count": 569, "country": "Russian Federation"}, "NL": {"count": 833, "country": "Netherlands"}, "NO": {"count": 221, "country": "Norway"}, "NC": {"count": 2, "country": "New Caledonia"}, "NZ": {"count": 30, "country": "New Zealand"}, "PA": {"count": 14, "country": "Panama"}, "RO": {"count": 56, "country": "Romania"}, "GU": {"count": 2, "country": "Guam"}, "GT": {"count": 10, "country": "Guatemala"}, "CO": {"count": 84, "country": "Colombia"}, "GR": {"count": 46, "country": "Greece"}, "CL": {"count": 40, "country": "Chile"}, "CA": {"count": 336, "country": "Canada"}, "CZ": {"count": 261, "country": "Czech Republic"}, "CY": {"count": 2, "country": "Cyprus"}, "SX": {"count": 1, "country": "Sint Maarten (Dutch)"}, "GB": {"count": 441, "country": "United Kingdom"}, "CR": {"count": 34, "country": "Costa Rica"}, "GP": {"count": 2, "country": "Guadeloupe"}, "GL": {"count": 3, "country": "Greenland"}, "CW": {"count": 3, "country": "Curacao"}, "TN": {"count": 15, "country": "Tunisia"}, "KE": {"count": 17, "country": "Kenya"}, "SV": {"count": 23, "country": "El Salvador"}, "SK": {"count": 73, "country": "Slovakia"}, "KR": {"count": 275, "country": "Korea, Republic Of"}, "SI": {"count": 11, "country": "Slovenia"}, "KW": {"count": 7, "country": "Kuwait"}, "SM": {"count": 2, "country": "San Marino"}, "KZ": {"count": 7, "country": "Kazakhstan"}, "SA": {"count": 7, "country": "Saudi Arabia"}, "SG": {"count": 38, "country": "Singapore"}, "SE": {"count": 321, "country": "Sweden"}, "DO": {"count": 2, "country": "Dominican Republic"}, "MN": {"count": 1, "country": "Mongolia"}, "DK": {"count": 125, "country": "Denmark"}, "HR": {"count": 6, "country": "Croatia"}, "DE": {"count": 398, "country": "Germany"}, "BA": {"count": 1, "country": "Bosnia And Herzegovina"}, "HU": {"count": 53, "country": "Hungary"}, "AT": {"count": 242, "country": "Austria"}, "HK": {"count": 37, "country": "Hong Kong"}, "CH": {"count": 262, "country": "Switzerland"}, "HN": {"count": 3, "country": "Honduras"}, "FI": {"count": 97, "country": "Finland"}, "CN": {"count": 70, "country": "China"}, "PR": {"count": 14, "country": "Puerto Rico"}, "PS": {"count": 1, "country": "Palestinian, State Of"}, "LC": {"count": 1, "country": "Saint Lucia"}, "PT": {"count": 18, "country": "Portugal"}, "TW": {"count": 196, "country": "Taiwan, Province Of "}, "PY": {"count": 3, "country": "Paraguay"}, "-": {"count": 103, "country": "-"}, "LI": {"count": 5, "country": "Liechtenstein"}, "LV": {"count": 5, "country": "Latvia"}, "LT": {"count": 8, "country": "Lithuania"}, "LU": {"count": 8, "country": "Luxembourg"}, "TH": {"count": 35, "country": "Thailand"}, "PE": {"count": 7, "country": "Peru"}, "PH": {"count": 4, "country": "Philippines"}, "EG": {"count": 32, "country": "Egypt"}, "PL": {"count": 140, "country": "Poland"}, "AE": {"count": 3, "country": "United Arab Emirates"}, "VE": {"count": 7, "country": "Venezuela, Bolivaria"}, "AG": {"count": 5, "country": "Antigua And Barbuda"}, "NI": {"count": 7, "country": "Nicaragua"}, "EE": {"count": 43, "country": "Estonia"}, "VI": {"count": 5, "country": "Virgin Islands, U.S."}, "IS": {"count": 19, "country": "Iceland"}, "IR": {"count": 6, "country": "Iran, Islamic Republic"}, "IT": {"count": 1206, "country": "Italy"}, "EC": {"count": 26, "country": "Ecuador"}, "ZA": {"count": 6, "country": "South Africa"}, "AR": {"count": 34, "country": "Argentina"}, "AU": {"count": 82, "country": "Australia"}, "VN": {"count": 96, "country": "Viet Nam"}, "AW": {"count": 5, "country": "Aruba"}, "IN": {"count": 80, "country": "India"}, "AX": {"count": 1, "country": "Aland Islands"}, "AD": {"count": 2, "country": "Andorra"}, "AZ": {"count": 6, "country": "Azerbaijan"}, "IE": {"count": 67, "country": "Ireland"}, "ID": {"count": 60, "country": "Indonesia"}, "ES": {"count": 281, "country": "Spain"}, "AL": {"count": 2, "country": "Albania"}, "MD": {"count": 1, "country": "Moldova, Republic Of"}, "UY": {"count": 4, "country": "Uruguay"}, "MC": {"count": 4, "country": "Monaco"}, "GF": {"count": 1, "country": "French Guiana"}, "MY": {"count": 8, "country": "Malaysia"}, "MO": {"count": 2, "country": "Macao"}, "RS": {"count": 27, "country": "Serbia"}, "GE": {"count": 2, "country": "Georgia"}, "US": {"count": 5489, "country": "United States"}, "MT": {"count": 1, "country": "Malta"}, "MQ": {"count": 1, "country": "Martinique"}, "UA": {"count": 56, "country": "Ukraine"}, "MX": {"count": 226, "country": "Mexico"}, "IL": {"count": 30, "country": "Israel"}}}
Необходимо данную строку с конвертировать в некий массив объектов. В моем случае это что то на подобии:

Код:
 List<Country> myList;
    public class Country 
    {
        public string Abbr { get; set; }
        public string Count { get; set; }
        public string Name { get; set; }
    }
Пробовал с помощью Newtonsoft.Json. Но превратить в нужный мне объект мешают аббревиатуры. Причем вытащить их мне необходимо в первую очередь.
Delegat вне форума Ответить с цитированием
Старый 27.02.2016, 00:24   #2
Alex11223
Старожил
 
Аватар для Alex11223
 
Регистрация: 12.01.2011
Сообщений: 19,500
По умолчанию

Как именно мешают?
Ушел с форума, https://www.programmersforum.rocks, alex.pantec@gmail.com, https://github.com/AlexP11223
ЛС отключены Аларом.
Alex11223 вне форума Ответить с цитированием
Старый 27.02.2016, 00:34   #3
Delegat
 
Регистрация: 16.04.2009
Сообщений: 9
По умолчанию

Если бы строка была вида
Цитата:
{"status": "success", "countries": {"AB": {"count": 2, "country": "Bangladesh"}, "AB": {"count": 124, "country": "Belgium"}, "AB": {"count": 761, "country": "France"}, "AB": {"count": 30, "country": "Bulgaria"}, "AB": {"count": 3, "country": "Morocco"}, "AB": {"count": 67, "country": "Turkey"}, "AB": {"count": 1, "country": "Brunei Darussalam"}, "AB": {"count": 3, "country": "Bolivia, Plurination"}...,
То все было бы просто.

Код:
    public class Abbr
    {
        public string count{ get; set; }
        public string country{ get; set; }
    }

public class Country
{
   public string status{get; set;}
   public List<Abbr> AB{get; set;}
}
List<Country> jsonObject = JsonReader.Deserialize<List<Country>>(json);
А у меня аббревиатуры разные и как их вытащить я уже замаялся искать.
Delegat вне форума Ответить с цитированием
Старый 27.02.2016, 00:41   #4
Alex11223
Старожил
 
Аватар для Alex11223
 
Регистрация: 12.01.2011
Сообщений: 19,500
По умолчанию

Ну всегда можно просто
Код:
dynamic jsonObj = JsonConvert.DeserializeObject(json);
или
Код:
JObject jsonObj = (JObject) JsonConvert.DeserializeObject(json);
и самому все доставать как нужно.
Ушел с форума, https://www.programmersforum.rocks, alex.pantec@gmail.com, https://github.com/AlexP11223
ЛС отключены Аларом.
Alex11223 вне форума Ответить с цитированием
Старый 27.02.2016, 00:52   #5
Delegat
 
Регистрация: 16.04.2009
Сообщений: 9
По умолчанию

Цитата:
Сообщение от Alex11223 Посмотреть сообщение
Ну всегда можно просто
Код:
dynamic jsonObj = JsonConvert.DeserializeObject(json);
или
Код:
JObject jsonObj = (JObject) JsonConvert.DeserializeObject(json);
и самому все доставать как нужно.
Это я тоже проходил. Но я не могу решить задачу как вытащить именно аббревиатуры.

То есть я могу спокойно получить отсюда jsonObj["countries"]["DE"] данные, но, само "DE" я не могу достать(
Delegat вне форума Ответить с цитированием
Старый 27.02.2016, 00:53   #6
Delegat
 
Регистрация: 16.04.2009
Сообщений: 9
По умолчанию

Уточню что строка постоянно меняется и мне каждый раз необходимо пользоваться перебором.
Delegat вне форума Ответить с цитированием
Старый 27.02.2016, 01:10   #7
Alex11223
Старожил
 
Аватар для Alex11223
 
Регистрация: 12.01.2011
Сообщений: 19,500
По умолчанию

Код:
            dynamic jsonObj = JsonConvert.DeserializeObject(json);

            var countries = (JObject) jsonObj.countries;

            foreach (var country in countries)
            {
                Console.WriteLine(country.Key);

                dynamic values = country.Value;

                Console.WriteLine(values.country);
            }
Ушел с форума, https://www.programmersforum.rocks, alex.pantec@gmail.com, https://github.com/AlexP11223
ЛС отключены Аларом.
Alex11223 вне форума Ответить с цитированием
Старый 27.02.2016, 01:14   #8
Delegat
 
Регистрация: 16.04.2009
Сообщений: 9
По умолчанию

Спасибо за помощь )
Delegat вне форума Ответить с цитированием
Старый 27.02.2016, 10:01   #9
Delegat
 
Регистрация: 16.04.2009
Сообщений: 9
По умолчанию

Получилось сделать немного по другому, но за наводку огромное спасибо еще раз!
Код:
                JToken outer = JToken.Parse(json);
                JObject inner = outer["countries"].Value<JObject>();

                List<string> keys = inner.Properties().Select(p => p.Name).ToList();

                foreach (string k in keys)
                {
                    Console.WriteLine(k); // KEY
                    Console.WriteLine(inner[k]); // VALUE
                }
Delegat вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
JSON Exception [org.apache.json] spectrum988 Помощь студентам 3 11.12.2015 09:25
JSON положить объект в объект Dozent Общие вопросы Delphi 7 30.03.2015 12:57
Передача JSON-строки из PHP в JavaScript Voronar JavaScript, Ajax 5 09.02.2013 19:00
Итерация через объект JSON в Javascript maomam Помощь студентам 0 03.11.2012 00:51
Как в JSON выразить объект? Utkin Общие вопросы по программированию, компьютерный форум 6 16.06.2012 00:01