Trouble deserializing JSON to a C# object

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

Trouble deserializing JSON to a C# object

问题

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

Crypto对象

public class Crypto
{
    public string? Symbol { get; set; }
    public string? Name { get; set; }
    public double? Price { get; set; }
    public double? ChangesPercentage { get; set; }
}

API调用服务接口

public interface ICryptoService
{
    Task<Crypto> GetCrypto(string symbol); 
}

API调用服务

public async Task<Crypto> GetCrypto(string symbol)
{
    using (HttpClient client = new HttpClient())
    {
        using var response = await client.GetAsync("https://financialmodelingprep.com/api/v3/quote/BTCUSD?apikey=KEY", HttpCompletionOption.ResponseHeadersRead);

        response.EnsureSuccessStatusCode();

        if (response.Content is object && response.Content.Headers.ContentType.MediaType == "application/json")
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            try
            {
                return await System.Text.Json.JsonSerializer.DeserializeAsync<Crypto>(responseStream, new System.Text.Json.JsonSerializerOptions { IgnoreNullValues = true, PropertyNameCaseInsensitive = true });
            }
            catch (JsonException)
            {
                Console.WriteLine("Invalid JSON!");
            }
        }
        else
        {
            Console.WriteLine("HTTP Response cannot be deserialised");
        }

        return null;
    }
}

主方法

CryptoService cryptoService = new CryptoService();

cryptoService.GetCrypto("BTCUSD").ContinueWith((task) =>
{
    var crypto = task.Result;
});

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

[
 {
    "symbol": "BTCUSD",
    "name": "Bitcoin USD",
    "price": 22887.08,
    "changesPercentage": -0.1263,
    "change": -28.9473,
    "dayLow": 22887.08,
    "dayHigh": 23351.51,
    "yearHigh": 48086.836,
    "yearLow": 15599.047,
    "marketCap": 441375461059,
    "priceAvg50": 19835.04,
    "priceAvg200": 19730.518,
    "volume": 27292504064,
    "avgVolume": 23965132574,
    "exchange": "CRYPTO",
    "open": 23267.4,
    "previousClose": 23267.4,
    "eps": null,
    "pe": null,
    "earningsAnnouncement": null,
    "sharesOutstanding": 19284918,
    "timestamp": 1675872360
 }
]

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

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

public class Crypto
{
    public string? Symbol { get; set; }
    public string? Name { get; set; }
    public double? Price { get; set; }
    public double? ChangesPercentage { get; set; }
}

API Call Service Interface

public interface ICryptoService
{
    Task&lt;Crypto&gt; GetCrypto(string symbol); 
}

API Call Service

public async Task&lt;Crypto&gt; GetCrypto(string symbol)
    {
        using (HttpClient client = new HttpClient())
        {
            using var response = await client.GetAsync(&quot;https://financialmodelingprep.com/api/v3/quote/BTCUSD?apikey=KEY&quot;, HttpCompletionOption.ResponseHeadersRead);

            response.EnsureSuccessStatusCode();

            if (response.Content is object &amp;&amp; response.Content.Headers.ContentType.MediaType == &quot;application/json&quot;)
            {
                var responseStream = await response.Content.ReadAsStreamAsync();

                try
                {
                    return await System.Text.Json.JsonSerializer.DeserializeAsync&lt;Crypto&gt;(responseStream, new System.Text.Json.JsonSerializerOptions { IgnoreNullValues = true, PropertyNameCaseInsensitive = true });
                }
                catch (JsonException)
                {
                    Console.WriteLine(&quot;Invalid JSON!&quot;);
                }
            }
            else
            {
                Console.WriteLine(&quot;HTTP Response cannot be deserialised&quot;);
            }

            return null;
        }
    }
}

Main Method

        CryptoService cryptoService = new CryptoService();

        cryptoService.GetCrypto(&quot;BTCUSD&quot;).ContinueWith((task) =&gt;
        {
            var crypto = task.Result;
        });

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

[
 {
&quot;symbol&quot;: &quot;BTCUSD&quot;,
&quot;name&quot;: &quot;Bitcoin USD&quot;,
&quot;price&quot;: 22887.08,
&quot;changesPercentage&quot;: -0.1263,
&quot;change&quot;: -28.9473,
&quot;dayLow&quot;: 22887.08,
&quot;dayHigh&quot;: 23351.51,
&quot;yearHigh&quot;: 48086.836,
&quot;yearLow&quot;: 15599.047,
&quot;marketCap&quot;: 441375461059,
&quot;priceAvg50&quot;: 19835.04,
&quot;priceAvg200&quot;: 19730.518,
&quot;volume&quot;: 27292504064,
&quot;avgVolume&quot;: 23965132574,
&quot;exchange&quot;: &quot;CRYPTO&quot;,
&quot;open&quot;: 23267.4,
&quot;previousClose&quot;: 23267.4,
&quot;eps&quot;: null,
&quot;pe&quot;: null,
&quot;earningsAnnouncement&quot;: null,
&quot;sharesOutstanding&quot;: 19284918,
&quot;timestamp&quot;: 1675872360
 }
]

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

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

答案1

得分: 1

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

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:

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:

确定