gpt4 book ai didi

C# 将 JSON 反序列化为对象

转载 作者:太空宇宙 更新时间:2023-11-03 23:08:45 25 4
gpt4 key购买 nike

我的 C# 程序有点问题。这是我在 C# 中的第一个程序,所以请原谅 :)

我想将我的 json 文件反序列化为对象,但我不知道我的类应该如何构建。我正在使用 Newtonsoft JSON 库。

JSON 文件:

http://api.nbp.pl/api/exchangerates/tables/A/last/?format=json


Form1.cs:

    private void button1_Click(object sender, EventArgs e)
{
CurrencyCodeValues k = new CurrencyCodeValues();
WebClient myWebClient = new WebClient();
dynamic result = myWebClient.DownloadString("http://api.nbp.pl/api/exchangerates/tables/A/last/?format=json");
IList<CurrencyCodeValues> m = JsonConvert.DeserializeObject<CurrencyCodeValues>(result);
}

Class1.cs:

class CurrencyCodeValues
{
public string table { get; set; }
public string no { get; set; }
public string effectiveDate { get; set; }
public List<rates_> rates { get; set; }

}

public class rates_
{
public string currency { get; set; }
public string code { get; set; }
public float mid { get; set; }
}

错误信息:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WindowsFormsApplication4.CurrencyCodeValues' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '', line 1, position 1.

最佳答案

根据你的错误信息,你的类(class)应该是这样的

public class Rootobject
{
public Class1[] Property1 { get; set; }
}

public class Class1
{
public string table { get; set; }
public string no { get; set; }
public string effectiveDate { get; set; }
public Rate[] rates { get; set; }
}

public class Rate
{
public string currency { get; set; }
public string code { get; set; }
public float mid { get; set; }
}

然后像这样反序列化

JsonConvert.DeserializeObject<Rootobject>(result);

关于C# 将 JSON 反序列化为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40212233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com