Форум программистов, компьютерный форум, киберфорум
C# .NET
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.67/6: Рейтинг темы: голосов - 6, средняя оценка - 4.67
0 / 0 / 0
Регистрация: 08.01.2018
Сообщений: 5

newtonsoft.json заполнение полей при десериализации своими значениями

20.12.2019, 12:08. Показов 1344. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Добрый день!
Нужен совет.
Есть класс для десериализации:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    class Order 
    {
        [JsonProperty("pair")]
        public string Pair { get; set; }
        [JsonProperty("trade_id")]
        public int OrderID { get; set; }
        [JsonProperty("type")]
        public string Type { get; set; }
        [JsonProperty("quantity")]
        public double Quantity { get; set; }
        [JsonProperty("price")]
        public double Price { get; set; }
        [JsonProperty("amount")]
        public double Amount { get; set; }
        [JsonProperty("date")]
        public int Date { get; set; }
    }
В JSON строке название валютной пары (pair) приходит в виде ключа объекта:
JSON
1
{"BTC_USD":[{"trade_id":132019291,"type":"buy","quantity":"0.12516","price":"7491.7693","amount":"937.66984558","date":1576830082},{"trade_id":132018752,"type":"buy","quantity":"0.130815","price":"7495.5315","amount":"980.52795317","date":1576830023},{"trade_id":132018629,"type":"sell","quantity":"0.12","price":"7492.1367","amount":"899.056404","date":1576830010},{"trade_id":132018026,"type":"sell","quantity":"0.120345","price":"7495.9053","amount":"902.09472332","date":1576829944},{"trade_id":132017952,"type":"buy","quantity":"0.00284799","price":"7499.99999576","amount":"21.35992498","date":1576829936},{"trade_id":132017433,"type":"buy","quantity":"0.00016182","price":"7499.99999908","amount":"1.21364999","date":1576829881},{"trade_id":132017270,"type":"sell","quantity":"0.156135","price":"7495.1799","amount":"1170.25991368","date":1576829861},{"trade_id":132016461,"type":"sell","quantity":"0.154305","price":"7492.7918","amount":"1156.17523869","date":1576829772},{"trade_id":132016315,"type":"buy","quantity":"0.12786","price":"7495.4102","amount":"958.36314817","date":1576829756},{"trade_id":132015806,"type":"buy","quantity":"0.153765","price":"7497.2488","amount":"1152.81446173","date":1576829700},{"trade_id":132015628,"type":"buy","quantity":"0.00403229","price":"7499.99999999","amount":"30.24217499","date":1576829679},{"trade_id":132015612,"type":"buy","quantity":"0.00622227","price":"7499.99999999","amount":"46.66702499","date":1576829678},{"trade_id":132015611,"type":"buy","quantity":"0.00277773","price":"7499.99999999","amount":"20.83297499","date":1576829678},{"trade_id":132014967,"type":"sell","quantity":"0.176685","price":"7487.3139","amount":"1322.89605642","date":1576829601},{"trade_id":132014555,"type":"buy","quantity":"0.00540661","price":"7499.99995007","amount":"40.54957473","date":1576829556},{"trade_id":132014485,"type":"buy","quantity":"0.16398","price":"7493.6933","amount":"1228.81582733","date":1576829546},{"trade_id":132014164,"type":"sell","quantity":"0.00867826","price":"7484.39348924","amount":"64.95151264","date":1576829513},{"trade_id":132014018,"type":"buy","quantity":"0.00089075","price":"7499.99999259","amount":"6.68062499","date":1576829497},{"trade_id":132013875,"type":"buy","quantity":"0.17388","price":"7495.5538","amount":"1303.32689474","date":1576829481},{"trade_id":132013673,"type":"buy","quantity":"0.00338527","price":"7494.09991606","amount":"25.36955162","date":1576829459},{"trade_id":132013652,"type":"buy","quantity":"0.00220258","price":"7494.09991947","amount":"16.5063546","date":1576829457},{"trade_id":132013602,"type":"buy","quantity":"0.00415933","price":"7494.09992515","amount":"31.17043464","date":1576829452},{"trade_id":132013359,"type":"buy","quantity":"0.00333278","price":"7494.09995585","amount":"24.97618645","date":1576829425},{"trade_id":132013295,"type":"buy","quantity":"0.00201172","price":"7494.09996268","amount":"15.07603077","date":1576829420},{"trade_id":132013281,"type":"buy","quantity":"0.00341708","price":"7494.09996379","amount":"25.6079391","date":1576829419},{"trade_id":132013243,"type":"buy","quantity":"0.154575","price":"7489.7569","amount":"1157.72917281","date":1576829413},{"trade_id":132012906,"type":"buy","quantity":"0.01552758","price":"7489.89999973","amount":"116.30002143","date":1576829379},{"trade_id":132012673,"type":"sell","quantity":"0.13362","price":"7485.236","amount":"1000.17723432","date":1576829351},{"trade_id":132012396,"type":"sell","quantity":"0.00867679","price":"7490","amount":"64.9891571","date":1576829320},{"trade_id":132012395,"type":"sell","quantity":"0.01890349","price":"7490.00000001","amount":"141.5871401","date":1576829320},{"trade_id":132012289,"type":"sell","quantity":"0.04","price":"7490","amount":"299.6","date":1576829308},{"trade_id":132012288,"type":"buy","quantity":"0.01890349","price":"7490.69998791","amount":"141.60037231","date":1576829308},{"trade_id":132012285,"type":"sell","quantity":"0.12318","price":"7490.0748","amount":"922.62741386","date":1576829308},{"trade_id":132012177,"type":"sell","quantity":"0.04","price":"7490","amount":"299.6","date":1576829297},{"trade_id":132012086,"type":"sell","quantity":"0.04","price":"7490","amount":"299.6","date":1576829286},{"trade_id":132012052,"type":"sell","quantity":"0.0004719","price":"7490","amount":"3.534531","date":1576829283},{"trade_id":132011989,"type":"sell","quantity":"0.04","price":"7490","amount":"299.6","date":1576829275},{"trade_id":132011875,"type":"sell","quantity":"0.04","price":"7490","amount":"299.6","date":1576829263},{"trade_id":132011826,"type":"buy","quantity":"0.13227","price":"7490.5444","amount":"990.77430778","date":1576829258},{"trade_id":132011755,"type":"sell","quantity":"0.04","price":"7490","amount":"299.6","date":1576829252},{"trade_id":132011663,"type":"sell","quantity":"0.04","price":"7490","amount":"299.6","date":1576829241},{"trade_id":132011568,"type":"sell","quantity":"0.04","price":"7490","amount":"299.6","date":1576829230},{"trade_id":132011459,"type":"sell","quantity":"0.04","price":"7490","amount":"299.6","date":1576829217},{"trade_id":132011345,"type":"sell","quantity":"0.04","price":"7490","amount":"299.6","date":1576829206},{"trade_id":132011237,"type":"sell","quantity":"0.03869161","price":"7490","amount":"289.8001589","date":1576829195},{"trade_id":132011236,"type":"sell","quantity":"0.00130839","price":"7490.00000001","amount":"9.7998411","date":1576829195},{"trade_id":132011188,"type":"buy","quantity":"0.00130839","price":"7490.69999835","amount":"9.80075697","date":1576829188},{"trade_id":132011136,"type":"sell","quantity":"0.04","price":"7490","amount":"299.6","date":1576829183},{"trade_id":132011097,"type":"buy","quantity":"0.159555","price":"7490.4659","amount":"1195.14128667","date":1576829180},{"trade_id":132010786,"type":"sell","quantity":"0.154575","price":"7490.2772","amount":"1157.80959819","date":1576829146},{"trade_id":132010622,"type":"sell","quantity":"0.012","price":"7490","amount":"89.88","date":1576829126},{"trade_id":132010621,"type":"sell","quantity":"0.028","price":"7490.00000001","amount":"209.72","date":1576829126},{"trade_id":132010520,"type":"sell","quantity":"0.01001331","price":"7490","amount":"74.9996919","date":1576829114},{"trade_id":132010519,"type":"sell","quantity":"0.00198669","price":"7490.00000001","amount":"14.8803081","date":1576829114},{"trade_id":132010518,"type":"sell","quantity":"0.028","price":"7490.00000001","amount":"209.72","date":1576829114},{"trade_id":132010504,"type":"buy","quantity":"0.010396","price":"7490.79999999","amount":"77.87435679","date":1576829113},{"trade_id":132010367,"type":"buy","quantity":"0.00661382","price":"7490.79999999","amount":"49.54280285","date":1576829097},{"trade_id":132010335,"type":"buy","quantity":"0.00765675","price":"7490.79999999","amount":"57.35518289","date":1576829095},{"trade_id":132010295,"type":"buy","quantity":"0.00593275","price":"7490.79999999","amount":"44.44104369","date":1576829092},{"trade_id":132010203,"type":"buy","quantity":"0.00380417","price":"7490.79999999","amount":"28.49627663","date":1576829082},{"trade_id":132010146,"type":"buy","quantity":"0.00478563","price":"7490.79999999","amount":"35.8481972","date":1576829076},{"trade_id":132010131,"type":"buy","quantity":"0.00165713","price":"7490.79999999","amount":"12.4132294","date":1576829075},{"trade_id":132010130,"type":"buy","quantity":"0.00212422","price":"7490.79999998","amount":"15.91210717","date":1576829075},{"trade_id":132010102,"type":"buy","quantity":"0.00673989","price":"7490.79999998","amount":"50.48716801","date":1576829073},{"trade_id":132010095,"type":"sell","quantity":"0.122685","price":"7490.1564","amount":"918.92983793","date":1576829073},{"trade_id":132010082,"type":"buy","quantity":"0.00673989","price":"7490.7999999","amount":"50.48716801","date":1576829071},{"trade_id":132010075,"type":"buy","quantity":"0.00736662","price":"7490.79999997","amount":"55.18187709","date":1576829070},{"trade_id":132010074,"type":"buy","quantity":"0.00904682","price":"7490.79999997","amount":"67.76791925","date":1576829070},{"trade_id":132010070,"type":"buy","quantity":"0.00198669","price":"7490.79999998","amount":"14.88189745","date":1576829070},{"trade_id":132010065,"type":"buy","quantity":"0.002","price":"7490.79999999","amount":"14.98159999","date":1576829070},{"trade_id":132010064,"type":"buy","quantity":"0.028","price":"7490.79999999","amount":"209.74239999","date":1576829070},{"trade_id":132009979,"type":"buy","quantity":"0.007794","price":"7494.69995313","amount":"58.41369143","date":1576829062},{"trade_id":132009953,"type":"buy","quantity":"0.00012664","price":"7494.69995474","amount":"0.9491288","date":1576829060},{"trade_id":132009946,"type":"buy","quantity":"0.010396","price":"7494.69995475","amount":"77.91490072","date":1576829059},{"trade_id":132009935,"type":"sell","quantity":"0.004206","price":"7490.00600013","amount":"31.50296523","date":1576829058},{"trade_id":132009934,"type":"sell","quantity":"0.028","price":"7490.00600016","amount":"209.720168","date":1576829058},{"trade_id":132009933,"type":"sell","quantity":"0.007794","price":"7490.00600016","amount":"58.37710676","date":1576829058},{"trade_id":132009923,"type":"buy","quantity":"0.00645061","price":"7494.69995666","amount":"48.34538648","date":1576829058},{"trade_id":132009922,"type":"buy","quantity":"0.0069522","price":"7494.69995665","amount":"52.10465303","date":1576829058},{"trade_id":132009919,"type":"buy","quantity":"0.010396","price":"7494.69995667","amount":"77.91490074","date":1576829057},{"trade_id":132009897,"type":"buy","quantity":"0.010392","price":"7494.69996044","amount":"77.88492198","date":1576829053},{"trade_id":132009874,"type":"buy","quantity":"0.007794","price":"7494.69996269","amount":"58.4136915","date":1576829051},{"trade_id":132009867,"type":"buy","quantity":"0.00155047","price":"7494.6999633","amount":"11.62030745","date":1576829051},{"trade_id":132009858,"type":"buy","quantity":"0.0002598","price":"7494.69996334","amount":"1.94712305","date":1576829051},{"trade_id":132009832,"type":"buy","quantity":"0.0127351","price":"7494.69996353","amount":"95.4457535","date":1576829048},{"trade_id":132009425,"type":"sell","quantity":"0.01","price":"7499","amount":"74.99","date":1576829003},{"trade_id":132009317,"type":"sell","quantity":"0.04","price":"7499.00700014","amount":"299.96028","date":1576828991},{"trade_id":132009257,"type":"sell","quantity":"0.158295","price":"7499.298","amount":"1187.10137691","date":1576828985},{"trade_id":132009223,"type":"sell","quantity":"0.04","price":"7499.00700014","amount":"299.96028","date":1576828980},{"trade_id":132009102,"type":"sell","quantity":"0.012","price":"7499.00600012","amount":"89.988072","date":1576828969},{"trade_id":132009101,"type":"sell","quantity":"0.028","price":"7499.00600013","amount":"209.972168","date":1576828969},{"trade_id":132009067,"type":"buy","quantity":"0.03866666","price":"7499.99999712","amount":"289.99994988","date":1576828963},{"trade_id":132009066,"type":"buy","quantity":"0.028","price":"7499.99999711","amount":"209.99999991","date":1576828963},{"trade_id":132008995,"type":"sell","quantity":"0.04","price":"7499.00100002","amount":"299.96004","date":1576828957},{"trade_id":132008870,"type":"sell","quantity":"0.04","price":"7499.00100002","amount":"299.96004","date":1576828943},{"trade_id":132008785,"type":"sell","quantity":"0.00480275","price":"7499.00100002","amount":"36.01582705","date":1576828933},{"trade_id":132008776,"type":"sell","quantity":"0.0001","price":"7499.00100003","amount":"0.7499001","date":1576828932},{"trade_id":132008775,"type":"sell","quantity":"0.00154988","price":"7499.00100003","amount":"11.62255166","date":1576828932},{"trade_id":132008774,"type":"sell","quantity":"0.00635878","price":"7499.00100003","amount":"47.68449757","date":1576828932},{"trade_id":132008753,"type":"buy","quantity":"0.0001","price":"7499.99999977","amount":"0.74999999","date":1576828930}]}
Задача состоит в том, чтобы заполнить все поля класса Order при десериализации, в том числе поле Pair.
Как я могу это сделать:
C#
1
2
3
4
5
6
7
8
9
10
11
12
            JObject jObject = JObject.Parse(JSON);
            Dictionary<string, List<Order>> dict = new Dictionary<string, List<Order>>();
            foreach (var pair in jObject)
            {
                List<Order> orders = new List<Order>();
                foreach (var order in pair.Value.ToObject<List<Order>>())
                {
                    order.Pair = pair.Key;
                    orders.Add(order);
                }
                dict.Add(pair.Key, orders);
            }
Хочется сделать так, чтобы поле Pair заполнялось уже во время десериализации, т.е. работал вот такой код:
C#
1
2
            JObject jObject = JObject.Parse(JSON);
            Dictionary<string, List<Order>> dict = jObject.ToObject<Dictionary<string, List<Order>>>();
Куда копать?..
Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.Collections.Generic;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System.Reflection;
 
namespace JSONObjects
{
    class Order 
    {
        [JsonProperty("pair")]
        public string Pair { get; set; }
        [JsonProperty("trade_id")]
        public int OrderID { get; set; }
        [JsonProperty("type")]
        public string Type { get; set; }
        [JsonProperty("quantity")]
        public double Quantity { get; set; }
        [JsonProperty("price")]
        public double Price { get; set; }
        [JsonProperty("amount")]
        public double Amount { get; set; }
        [JsonProperty("date")]
        //[JsonConverter(typeof(UnixTimeToDatetimeConverter))]
        public int Date { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var wb = new WebClient();
            string request = "https://api.exmo.com/v1/trades/?pair=BTC_USD";
            string answer = wb.DownloadString(request);
            JObject jObject = JObject.Parse(answer);
 
            Dictionary<string, List<Order>> dict = jObject.ToObject<Dictionary<string, List<Order>>>();
        }
    }
}
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
20.12.2019, 12:08
Ответы с готовыми решениями:

Сереализация отдельных полей класса в NewtonSoft.Json
Добрый день коллеги! Есть несколько разных JSON пакетов с одинаковым именем ключа, но в для разных пакетов - разным набором значений...

Можно ли в Newtonsoft JSON задать различные имена свойств для сериализации/десериализации?
Есть ли в Newtonsoft JSON средства, при помощи которых можно задать различные имена свойств для сериализации/десериализации. ...

Null reference при десерелизации JSON (Newtonsoft.Json)
Задача: достать из JSON ответа Название фирмы. Использую библиотеку Newtonsoft.Json. Сам код: //Выполняю запрос HttpWebRequest...

1
Заблокирован
20.12.2019, 14:32
Вот что-то очень похожее:
https://stackoverflow.com/ques... ring-value
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
20.12.2019, 14:32
Помогаю со студенческими работами здесь

Не находится библиотека Newtonsoft.Json при запуске из архива
Добрый день На ПК где стоит визуал студио комьюнити и где пишется приложение - всё работает. приложение windows forms. Если скинуть на...

Ошибка формата при десериализации json
Json: Я так понимаю projects это массив Классы в C#

Верификация файла .json и .xml при десериализации
Собственно проблема такая: нужно обработать импорт некорректного файла. Файлы содержат объекты базового класса собранные в...

При десериализации JSON из файла происходит ошибка
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using...

Ошибка при десериализации json файла в list
Здравствуйте. У меня проблема с десериализации. Вот таким способом я делаю: var json = new...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод. Thinkpad X220 Tablet —. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru