英文:
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<Crypto> GetCrypto(string symbol);
}
API Call Service
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;
}
}
}
Main Method
CryptoService cryptoService = new CryptoService();
cryptoService.GetCrypto("BTCUSD").ContinueWith((task) =>
{
var crypto = task.Result;
});
I am attaching the JSON response that the link will provide below:
[
{
"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
}
]
This is the exception that I get whenever I run the code:
Exception thrown: 'System.Text.Json.JsonException' in System.Private.CoreLib.dll
答案1
得分: 1
你的 JSON 是一个 JSON 数组,而不是一个单独的 JSON 对象,因此你需要反序列化为一个集合:
var result = await JsonSerializer.DeserializeAsync<List<Crypto>>(...);
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<List<Crypto>>(...);
P.S.
In general case it is recommended to just await
async functions instead of using ContinueWith
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论