简体   繁体   English

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

[英]System.Text.Json check if array is null

I'm just new in using Sytem.Text.Json .我刚开始使用Sytem.Text.Json

How I can check if the subscriptions array is empty or null ?如何检查subscriptions数组是空还是null

JSON: JSON:

{
    "user": {
        "id": "35812913u",
        "subscriptions": [] //check if null
    }
}

and this is what I want to check if it is null.这就是我想检查它是否为空的内容。

if (subscriptions != null) {
    
}

First of all you should have some classes to deserialize your json into:首先,您应该有一些类将您的 json 反序列化为:

    public class Rootobject
    {
        public User User { get; set; }
    }

    public class User
    {
        public string Id { get; set; }
        public string[] Subscriptions { get; set; }
    }

In my example I am reading the content from a file called data.json and pass it to the JsonSerializer , checking properties for null using the Null-conditional operator :在我的示例中,我从名为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
            }
        }
    }

If you need to get the data from an API, you can use the extension methods over the HttpClient , but I would suggest to use IHttpClientFactory to create your client:如果您需要从 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
    }

You can do it using JsonDocument too, by making use of GetProperty() , or even better, TryGetProperty() methods:您也可以通过使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM