[英]System.Text.Json check if array is null
我剛開始使用Sytem.Text.Json 。
如何檢查subscriptions
數組是空還是null
?
JSON:
{
"user": {
"id": "35812913u",
"subscriptions": [] //check if null
}
}
這就是我想檢查它是否為空的內容。
if (subscriptions != null) {
}
首先,您應該有一些類將您的 json 反序列化為:
public class Rootobject
{
public User User { get; set; }
}
public class User
{
public string Id { get; set; }
public string[] Subscriptions { get; set; }
}
在我的示例中,我從名為data.json
的文件中讀取內容並將其傳遞給JsonSerializer
,使用Null 條件運算符檢查 null 屬性:
private static async Task ProcessFile()
{
var file = Path.Combine(Directory.GetCurrentDirectory(), "data.json");
if (File.Exists(file))
{
var text = await File.ReadAllTextAsync(file);
var result = JsonSerializer.Deserialize<Rootobject>(text, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
if (result?.User?.Subscriptions?.Length > 0)
{
// do something
}
else
{
// array is empty
}
}
}
如果您需要從 API 獲取數據,您可以使用HttpClient
的擴展方法,但我建議使用IHttpClientFactory來創建您的客戶端:
var client = new HttpClient();
var result = await client.GetFromJsonAsync<Rootobject>("https://some.api.com");
if (result?.User?.Subscriptions?.Length > 0)
{
// do something
}
else
{
// array is empty
}
您也可以通過使用GetProperty()
或更好的TryGetProperty()
方法使用JsonDocument
來做到這一點:
private static async Task WithJsonDocument()
{
var file = Path.Combine(Directory.GetCurrentDirectory(), "data.json");
if (File.Exists(file))
{
var text = await File.ReadAllBytesAsync(file);
using var stream = new MemoryStream(text);
using var document = await JsonDocument.ParseAsync(stream);
var root = document.RootElement;
var user = root.GetProperty("user");
var subscriptions = user.GetProperty("subscriptions");
var subs = new List<string>();
if (subscriptions.GetArrayLength() > 0)
{
foreach (var sub in subscriptions.EnumerateArray())
{
subs.Add(sub.GetString());
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.