如何将JSON转换为C#中的自定义对象类并访问属性
我对c#非常陌生,我正试图操纵api restcountries.eu中的数据。我在确定将代码准确放置在何处以转换数据时遇到问题。我期望的结果是通过控制台显示特定国家的货币名称(由3位字母代码标识)如何将JSON转换为C#中的自定义对象类并访问属性,c#,json,C#,Json,我对c#非常陌生,我正试图操纵api restcountries.eu中的数据。我在确定将代码准确放置在何处以转换数据时遇到问题。我期望的结果是通过控制台显示特定国家的货币名称(由3位字母代码标识) using System; using System.Net; using System.Text; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Co
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();
}
}
}
无法将当前JSON数组(例如[1,2,3])反序列化为类型“apipracture.Currency”,因为该类型需要一个JSON对象(例如{“name”:“value”})才能正确反序列化。要修复此错误,请将JSON更改为JSON对象(例如{“name”:“value”}),或将反序列化类型更改为数组或实现可从JSON数组反序列化的集合接口(例如ICollection、IList)类似列表的类型。还可以将JsonArrayAttribute添加到类型中,以强制它从JSON数组反序列化。路径“货币”,第1行,位置581
该错误意味着JSON的属性“货币”是一个数组,但在类国家/地区中,属性货币的类型是对象货币。您必须将属性货币的类型从货币更改为货币列表
您物业的代码应为:
public IList<Currency> Currencies { get; set; }
公共IList货币{get;set;}
此外,在类的构造函数中初始化列表是一种很好的做法。因此,在类国家/地区中,必须实现以下构造函数:
public Country() {
Currencies = new List<Currency>();
}
public Country(){
货币=新列表();
}
嗯,JSON对理解你的问题很有用。当然,我刚刚在原始帖子中添加了它。谢谢您是否使用任何JSON库,例如Newtonsoft?JSON中的“货币”是一个数组,但类的属性是一个类型。试着把它从货币改成清单。是的,我是。虽然我在GetCountryAsync()方法中没有成功实现它,但我真的不知道为什么。我在反序列化JSON输出时运气不佳,这让我抓狂。
public Country() {
Currencies = new List<Currency>();
}