im试图访问我从解析JSON获得的对象列表的属性,但是我什至不确定它是否正确解析了。这是我的代码:
public class Currency
{
public int Broj_tecajnice { get; set; }
public string Drzava { get; set; }
public string Drzava_iso { get; set; }
public string Sifra_valute { get; set; }
public string Valuta { get; set; }
public int Jedinica { get; set; }
public float Kupovni_tecaj { get; set; }
public float Srednji_tecaj { get; set; }
public float Prodajni_tecaj { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (WebClient webClient = new System.Net.WebClient())
{
WebClient client = new WebClient();
var json =
client.DownloadString("http://api.hnb.hr/tecajn/v2");
List<Currency> currencies =
JsonConvert.DeserializeObject<List<Currency>>(json);
currencies.ForEach(c =>
Console.WriteLine(currencies.ToString()));
}
}
}
,简而言之,API看起来像这样:
[{"broj_tecajnice":"85","datum_primjene":"2019-05-01","drzava":"EMU","drzava_iso":"EMU","sifra_valute":"978","valuta":"EUR","jedinica":1,"kupovni_tecaj":"7,388924","srednji_tecaj":"7,411157","prodajni_tecaj":"7,433390"}, {"broj_tecajnice":"85","datum_primjene":"2019-05-01","drzava":"EMU","drzava_iso":"EMU","sifra_valute":"978","valuta":"EUR","jedinica":1,"kupovni_tecaj":"7,388924","srednji_tecaj":"7,411157","prodajni_tecaj":"7,433390"}]
等等,它有14个对象,我设法在列表中获取所有14个对象,但我无法访问对象属性
字符串呼叫看起来不正确。您需要使用集合中对象的属性构造字符串。
例如
currencies.ForEach(c =>
Console.WriteLine($"drzava_iso: {c.Drzava_iso}, Sifra_valute: {c.Sifra_valute}, ...")
);
其他一切看起来都应该。
您必须在ForEach
函数的Action
中使用c
参数:
如果您的Currency
类中有Overriden ToString
:
currencies.ForEach(c => Console.WriteLine(c.ToString()));
否则,您可以致电委托:
currencies.ForEach(delegate(Currency c)
{
// make your ToString() function here or any other code
Console.WriteLine(c.Broj_tecajnice);
});
阅读更多abour ForEach
:https://learn.microsoft.com/fr-fr/dotnet/api/system.collections.generic.generic.list-1.foreach?view=netframework.netframework-4.7