Я очень новичок в c# и пытаюсь манипулировать данными из API restcountries.eu. У меня есть проблемы, определяющие, где именно разместить код для преобразования данных. Мой желаемый результат заключается в отображении названия валюты определенной c страны (идентифицируемой 3-ди git альфа-кодом) через консоль.
using System;
using System.Net;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ApiPractice
{
public class Country
{
//Alpha3code
public string Alpha3Code { get; set; }
//country name
public string Name { get; set; }
//population
public int Population { get; set; }
//public string Languages { get; set; }
//flag
public string Flag { get; set; }
//timezone
public string[] TimeZones { get; set; }
//capital
public string Capital { get; set; }
//currency
public Currency Currencies { get; set; }
////bordering countries
public string[] Borders { get; set; }
}
public partial class Currency
{
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Symbol")]
public string Symbol { get; set; }
}
class Program
{
readonly static HttpClient client = new HttpClient();
static void ShowProduct(Country country)
{
Console.WriteLine(country.Currencies.Name);
}
static string ConvertStringArrayToString(string[] array)
{
// Concatenate all the elements into a StringBuilder.
StringBuilder builder = new StringBuilder();
foreach (string value in array)
{
builder.Append(value);
builder.Append(',');
}
return builder.ToString();
}
static async Task<Country> GetCountryAsync(string path)
{
Country country = null;
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
country = await response.Content.ReadAsAsync<Country>();
}
return country;
}
static void Main()
{
RunAsync().GetAwaiter().GetResult();
}
static async Task RunAsync()
{
// Update port # in the following line.
client.BaseAddress = new Uri("https://restcountries.eu/rest/v2/alpha/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
try
{
Console.WriteLine("Please write the alpha numeric code for the country requested");
var alphacode= Console.ReadLine();
// Get the product
var product = await GetCountryAsync(alphacode);
ShowProduct(product);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}
В настоящее время это сообщение об ошибке, которое я получаю в консоли:
Пожалуйста, напишите буквенный код c для запрашиваемой страны
usa
Невозможно десериализовать текущий массив JSON (например, [1,2,3]) в тип 'ApiPractice.Currency', поскольку для типа требуется объект JSON (например, значение {"name": " "}) для правильной десериализации.
Чтобы исправить эту ошибку, либо измените JSON на JSON объект (например, {" name ":" value "}), либо измените десериализованный тип на массив или тип, который реализует интерфейс коллекции (например, ICollection, IList), такой как List, который можно десериализовать из массива JSON. Атрибут JsonArrayAttribute также можно добавить к типу, чтобы принудительно десериализовать его из массива JSON.
Путь 'валюты', строка 1, позиция 581.
JSON:
{
"name": "United States of America",
"topLevelDomain": [
".us"
],
"alpha2Code": "US",
"alpha3Code": "USA",
"callingCodes": [
"1"
],
"capital": "Washington, D.C.",
"altSpellings": [
"US",
"USA",
"United States of America"
],
"region": "Americas",
"subregion": "Northern America",
"population": 323947000,
"latlng": [
38.0,
-97.0
],
"demonym": "American",
"area": 9629091.0,
"gini": 48.0,
"timezones": [
"UTC-12:00",
"UTC-11:00",
"UTC-10:00",
"UTC-09:00",
"UTC-08:00",
"UTC-07:00",
"UTC-06:00",
"UTC-05:00",
"UTC-04:00",
"UTC+10:00",
"UTC+12:00"
],
"borders": [
"CAN",
"MEX"
],
"nativeName": "United States",
"numericCode": "840",
"currencies": [
{
"code": "USD",
"name": "United States dollar",
"symbol": "$"
}
],
"languages": [
{
"iso639_1": "en",
"iso639_2": "eng",
"name": "English",
"nativeName": "English"
}
],
"translations": {
"de": "Vereinigte Staaten von Amerika",
"es": "Estados Unidos",
"fr": "États-Unis",
"ja": "アメリカ合衆国",
"it": "Stati Uniti D'America",
"br": "Estados Unidos",
"pt": "Estados Unidos",
"nl": "Verenigde Staten",
"hr": "Sjedinjene Američke Države",
"fa": "ایالات متحده آمریکا"
},
"flag": "https://restcountries.eu/data/usa.svg",
"regionalBlocs": [
{
"acronym": "NAFTA",
"name": "North American Free Trade Agreement",
"otherAcronyms": [],
"otherNames": [
"Tratado de Libre Comercio de América del Norte",
"Accord de Libre-échange Nord-Américain"
]
}
],
"cioc": "USA"
}