Trouble deserializing JSON to a C# object

huangapple go评论99阅读模式
英文:

Trouble deserializing JSON to a C# object

问题

我正在开发一个WPF MVVM应用程序,用于从此API获取一些加密货币信息。我能够调用API并获得HTTP响应,但我在将此响应反序列化为对象时遇到了问题。我理解传递了符号变量但未使用它,但我希望反序列化过程能够正常运行,然后我将相应地格式化URI以包含符号和API密钥。以下是代码:

Crypto对象

  1. public class Crypto
  2. {
  3. public string? Symbol { get; set; }
  4. public string? Name { get; set; }
  5. public double? Price { get; set; }
  6. public double? ChangesPercentage { get; set; }
  7. }

API调用服务接口

  1. public interface ICryptoService
  2. {
  3. Task<Crypto> GetCrypto(string symbol);
  4. }

API调用服务

  1. public async Task<Crypto> GetCrypto(string symbol)
  2. {
  3. using (HttpClient client = new HttpClient())
  4. {
  5. using var response = await client.GetAsync("https://financialmodelingprep.com/api/v3/quote/BTCUSD?apikey=KEY", HttpCompletionOption.ResponseHeadersRead);
  6. response.EnsureSuccessStatusCode();
  7. if (response.Content is object && response.Content.Headers.ContentType.MediaType == "application/json")
  8. {
  9. var responseStream = await response.Content.ReadAsStreamAsync();
  10. try
  11. {
  12. return await System.Text.Json.JsonSerializer.DeserializeAsync<Crypto>(responseStream, new System.Text.Json.JsonSerializerOptions { IgnoreNullValues = true, PropertyNameCaseInsensitive = true });
  13. }
  14. catch (JsonException)
  15. {
  16. Console.WriteLine("Invalid JSON!");
  17. }
  18. }
  19. else
  20. {
  21. Console.WriteLine("HTTP Response cannot be deserialised");
  22. }
  23. return null;
  24. }
  25. }

主方法

  1. CryptoService cryptoService = new CryptoService();
  2. cryptoService.GetCrypto("BTCUSD").ContinueWith((task) =>
  3. {
  4. var crypto = task.Result;
  5. });

我附上了链接将提供的JSON响应:

  1. [
  2. {
  3. "symbol": "BTCUSD",
  4. "name": "Bitcoin USD",
  5. "price": 22887.08,
  6. "changesPercentage": -0.1263,
  7. "change": -28.9473,
  8. "dayLow": 22887.08,
  9. "dayHigh": 23351.51,
  10. "yearHigh": 48086.836,
  11. "yearLow": 15599.047,
  12. "marketCap": 441375461059,
  13. "priceAvg50": 19835.04,
  14. "priceAvg200": 19730.518,
  15. "volume": 27292504064,
  16. "avgVolume": 23965132574,
  17. "exchange": "CRYPTO",
  18. "open": 23267.4,
  19. "previousClose": 23267.4,
  20. "eps": null,
  21. "pe": null,
  22. "earningsAnnouncement": null,
  23. "sharesOutstanding": 19284918,
  24. "timestamp": 1675872360
  25. }
  26. ]

这是我运行代码时遇到的异常:

  1. Exception thrown: 'System.Text.Json.JsonException' in System.Private.CoreLib.dll
英文:

I am working on a WPF MVVM application to retrieve some cryptocurrency information from this API. I am able to call the API and get an HTTP response, however, I am having trouble deserializing this response to an object. I understand that the symbol variable is passed but not used, however, I want the deserialization process to work and then I will format the URI accordingly to include the symbol and the API Key. Here is the code:

Crypto Object

  1. public class Crypto
  2. {
  3. public string? Symbol { get; set; }
  4. public string? Name { get; set; }
  5. public double? Price { get; set; }
  6. public double? ChangesPercentage { get; set; }
  7. }

API Call Service Interface

  1. public interface ICryptoService
  2. {
  3. Task&lt;Crypto&gt; GetCrypto(string symbol);
  4. }

API Call Service

  1. public async Task&lt;Crypto&gt; GetCrypto(string symbol)
  2. {
  3. using (HttpClient client = new HttpClient())
  4. {
  5. using var response = await client.GetAsync(&quot;https://financialmodelingprep.com/api/v3/quote/BTCUSD?apikey=KEY&quot;, HttpCompletionOption.ResponseHeadersRead);
  6. response.EnsureSuccessStatusCode();
  7. if (response.Content is object &amp;&amp; response.Content.Headers.ContentType.MediaType == &quot;application/json&quot;)
  8. {
  9. var responseStream = await response.Content.ReadAsStreamAsync();
  10. try
  11. {
  12. return await System.Text.Json.JsonSerializer.DeserializeAsync&lt;Crypto&gt;(responseStream, new System.Text.Json.JsonSerializerOptions { IgnoreNullValues = true, PropertyNameCaseInsensitive = true });
  13. }
  14. catch (JsonException)
  15. {
  16. Console.WriteLine(&quot;Invalid JSON!&quot;);
  17. }
  18. }
  19. else
  20. {
  21. Console.WriteLine(&quot;HTTP Response cannot be deserialised&quot;);
  22. }
  23. return null;
  24. }
  25. }
  26. }

Main Method

  1. CryptoService cryptoService = new CryptoService();
  2. cryptoService.GetCrypto(&quot;BTCUSD&quot;).ContinueWith((task) =&gt;
  3. {
  4. var crypto = task.Result;
  5. });

I am attaching the JSON response that the link will provide below:

  1. [
  2. {
  3. &quot;symbol&quot;: &quot;BTCUSD&quot;,
  4. &quot;name&quot;: &quot;Bitcoin USD&quot;,
  5. &quot;price&quot;: 22887.08,
  6. &quot;changesPercentage&quot;: -0.1263,
  7. &quot;change&quot;: -28.9473,
  8. &quot;dayLow&quot;: 22887.08,
  9. &quot;dayHigh&quot;: 23351.51,
  10. &quot;yearHigh&quot;: 48086.836,
  11. &quot;yearLow&quot;: 15599.047,
  12. &quot;marketCap&quot;: 441375461059,
  13. &quot;priceAvg50&quot;: 19835.04,
  14. &quot;priceAvg200&quot;: 19730.518,
  15. &quot;volume&quot;: 27292504064,
  16. &quot;avgVolume&quot;: 23965132574,
  17. &quot;exchange&quot;: &quot;CRYPTO&quot;,
  18. &quot;open&quot;: 23267.4,
  19. &quot;previousClose&quot;: 23267.4,
  20. &quot;eps&quot;: null,
  21. &quot;pe&quot;: null,
  22. &quot;earningsAnnouncement&quot;: null,
  23. &quot;sharesOutstanding&quot;: 19284918,
  24. &quot;timestamp&quot;: 1675872360
  25. }
  26. ]

This is the exception that I get whenever I run the code:

  1. Exception thrown: &#39;System.Text.Json.JsonException&#39; in System.Private.CoreLib.dll

答案1

得分: 1

你的 JSON 是一个 JSON 数组,而不是一个单独的 JSON 对象,因此你需要反序列化为一个集合:

  1. var result = await JsonSerializer.DeserializeAsync&lt;List&lt;Crypto&gt;&gt;(...);

P.S.

通常情况下,建议只使用 await 异步函数,而不是使用 ContinueWith

英文:

Your json is a json array, not a single json object, so you need to deserialize to a collection:

  1. var result = await JsonSerializer.DeserializeAsync&lt;List&lt;Crypto&gt;&gt;(...);

P.S.

In general case it is recommended to just await async functions instead of using ContinueWith.

huangapple
  • 本文由 发表于 2023年2月9日 02:33:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75390281.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定