[英]How to deserialize this JSON to a List?
我在將 JSON 文件從 web 反序列化為List
時遇到問題。
我的代碼在下面,但它不執行並顯示System.NullReferenceException
。 當我在列表中調用callApiAsync()
時,它發生在Content()
方法中。
class Program
{
static void Main(string[] args)
{
Content();
Console.ReadKey();
}
private async static void Content()
{
List<Coin> coins = await callApiAsync();
for (int i = 0; i < coins.Count; i++)
{
Console.WriteLine(coins[i].price);
}
}
static async Task<List<Coin>> callApiAsync()
{
string url = "https://api.coinstats.app/public/v1/charts?period=all&coinId=bitcoin";
HttpClient httpClient = new HttpClient();
var httpResponse = await httpClient.GetAsync(url);
string jsonResponse = await httpResponse.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<Root>(jsonResponse);
return data.coins;
}
}
public class Root
{
public List<Coin> coins { get; set; }
}
public class Coin
{
public int time { get; set; }
public int price { get; set; }
}
以我的JSON為例:
{
"chart":[
[
1372032000,
107.979,
1,
0
],
[
1372118400,
102.982,
1,
0
],
[
1372204800,
103.34,
1,
0
]
]
}
你給的樣品JSON:
{"chart":[[1372032000,107.979,1,0],[1372118400,102.982,1,0],[1372204800,103.34,1,0]]}
沒有與您嘗試反序列化到的“根”class 相匹配的類型。
你可以將你的 JSON 粘貼到像https://json2csharp.com/這樣的網站,看看對應的 C# class 應該是什么樣子。 在這種情況下, Root
class 應該如下所示以支持反序列化指定的 JSON:
public class Root
{
public List<List<double>> chart { get; set; }
}
我的猜測是您打算將每個列表中的第一個值解釋為某種時間戳,第二個值解釋為“價格”,並忽略每個列表中的第二個和第三個值。 在首先將 JSON 反序列化為雙打列表后,您將不得不為此做些跑腿工作。
例如:
var data = JsonConvert.DeserializeObject<Root>(jsonResponse);
return data.chart.Select(listOfDoubles => new Coin
{
time = (int)listOfDoubles[0],
price = listOfDoubles[1]
}).ToList();
反序列化只需要一串代碼
return JObject.Parse(jsonResponse)["chart"]
.Select(x => new Coin { time = UnixSecondsToDateTime( (long) x[0]),
price = (decimal)x[1] }
).ToList();
public class Coin
{
public DateTime time { get; set; }
public decimal price { get; set; }
}
public static DateTime UnixSecondsToDateTime(long timestamp, bool local = false)
{
var offset = DateTimeOffset.FromUnixTimeSeconds(timestamp);
return local ? offset.LocalDateTime : offset.UtcDateTime;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.