System.Text.Json 检查数组是否为空

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-conditional operator:

检查属性是否为 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
    }

您也可以使用 JsonDocument 来实现,方法是 GetProperty(),甚至更好,TryGetProperty() 方法:

    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());
                }
            }
        }
    }