Модераторы: Partizan, gambit
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> DeserializeObject из JSON string, Конвертирование JSON строки в объект 
:(
    Опции темы
Delegat
Дата 27.2.2016, 00:04 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 33
Регистрация: 20.3.2009
Где: Екатеринбург

Репутация: нет
Всего: нет



Добрый день. Имеется 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. Но превратить в нужный мне объект мешают аббревиатуры. Причем вытащить их мне необходимо в первую очередь.
PM MAIL WWW   Вверх
sgrey
Дата 28.2.2016, 02:01 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 265
Регистрация: 15.4.2006

Репутация: нет
Всего: 4



я бы структуру json поменял если есть возможность. Он не совсем правильно построен. countries должен быть массивом, содержащим объекты, а всё остальное - свойствами объектов.

Если ничего менять нельзя, то просто вручную напиши цикл, который будет каждый объект в нужную структуру загонять... Это будет самый простой и быстрый способ. 
PM MAIL   Вверх
mihryak
Дата 29.2.2016, 19:28 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 731
Регистрация: 28.4.2007
Где: С-Пб

Репутация: 19
Всего: 36



напрямую десериализовать в твой класс и правда не получится.
надо либо менять формат данных, либо приспасабливаться к имеющемуся контракту
Код

            var response = new JavaScriptSerializer().Deserialize<dynamic>(data);
            var countries = (Dictionary<string, object>)response["countries"];
            var countryList = countries.Select(p => new Country
            {
                Abbr = p.Key,
                Count = ((Dictionary<string, object>)p.Value)["count"].ToString(),
                Name = ((Dictionary<string, object>)p.Value)["country"].ToString(),
            }).ToList();

PM MAIL ICQ   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Прежде чем создать тему, посмотрите сюда:
mr.DUDA
THandle

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс "транслит" если у Вас нет русских шрифтов.
Что делать если Вам помогли, но отблагодарить помощника плюсом в репутацию Вы не можете(не хватает сообщений)? Пишите сюда, или отправляйте репорт. Поставим :)
Так же не забывайте отмечать свой вопрос решенным, если он таковым является :)


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, mr.DUDA, THandle.

 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Общие вопросы по .NET и C# | Следующая тема »


 




[ Время генерации скрипта: 0.0626 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.