У меня такой JSON:
{
"BTC_BCN": {
"id": 7,
"last": "0.00000019",
"lowestAsk": "0.00000020",
"highestBid": "0.00000019",
"percentChange": "0.00000000",
"baseVolume": "7.27124323",
"quoteVolume": "36958572.58593949",
"isFrozen": "0",
"high24hr": "0.00000020",
"low24hr": "0.00000019"
},
"BTC_BTS": {
"id": 14,
"last": "0.00001512",
"lowestAsk": "0.00001518",
"highestBid": "0.00001512",
"percentChange": "0.00000000",
"baseVolume": "3.82925362",
"quoteVolume": "253971.93868064",
"isFrozen": "0",
"high24hr": "0.00001525",
"low24hr": "0.00001495"
}
}
... Еще много записей.
Это моя модель:
public class GetInfoCoinsPoloniex
{
public int id { get; set; }
public string last { get; set; }
public string lowestAsk { get; set; }
public string highestBid { get; set; }
public string percentChange { get; set; }
public string baseVolume { get; set; }
public string quoteVolume { get; set; }
public string isFrozen { get; set; }
public string high24hr { get; set; }
public string low24hr { get; set; }
}
public class RootPoloniex
{
public GetInfoCoinsPoloniex symbol { get; set; }
}
И это мой Контроллер:
[Route("api/poloniex")]
[ApiController]
public class PoloniexController : ControllerBase
{
[HttpGet]
public async Task<IEnumerable<GetInfoCoinsPoloniex>> GetCoinsPoloniex()
{
string Baseurl = "https://poloniex.com";
string Parameters = "public?command=returnTicker";
List<GetInfoCoinsPoloniex> CoinsInfoPoloniex = new List<GetInfoCoinsPoloniex>();
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource GetAllEmployees using HttpClient
HttpResponseMessage Res = await client.GetAsync(Parameters);
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
string CoinResponse = Res.Content.ReadAsStringAsync().Result;
CoinsInfoPoloniex = JsonConvert.DeserializeObject<List<GetInfoCoinsPoloniex>>(CoinResponse);
}
return CoinsInfoPoloniex;
}
}
}
И я получаю эту ошибку:
JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Я думаю, моя проблема в том, что я неправильно обрабатываю структуру JSON. Somebady, помогите мне, пожалуйста ?. Большое спасибо.
Ваше объявление json - это объект, а не массив. Замените круглые скобки {} на [] и попробуйте





Это словарь, вам может подойти следующее:
CoinsInfoPoloniex = JsonConvert.DeserializeObject<Dictionary<string,GetInfoCoinsPoloniex>>(CoinResponse);
Большое спасибо. Как мы говорим в Колумбии, «вы спасли родину». Спасибо за уделенное время.
Замените List на Dictionary следующим образом:
Dictionary<string,GetInfoCoinsPoloniex> CoinsInfoPoloniex = new Dictionary<string,GetInfoCoinsPoloniex>();
затем используйте следующее:
CoinsInfoPoloniex = JsonConvert.DeserializeObject<Dictionary<string,GetInfoCoinsPoloniex>>(CoinResponse);
Подробно проработав ответ, данный @TheGeneral, если вы используете немного LINQ, как это,
JsonConvert.DeserializeObject<Dictionary<string,GetInfoCoinsPoloniex>>(CoinResponse).Select( o => new GetInfoCoinsPoloniex() { id = o.Key, ...}).ToList();
Это вернет вам список объектов GetInfoCoinsPoloniex непосредственно из файла json.
Edit: Can you accept the edit so i can take the dv back. I don't know how, i think by mistake i clicked and didn't realize and but still my apologies bro
Структура JSON представляет собой словарь / объект, вы не можете десериализовать его в массив, как указано в ошибке. Попробуйте вместо этого десериализацию в словарь