1

I'm just new in using Sytem.Text.Json.

How I can check if the subscriptions array is empty or null?

JSON:

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

and this is what I want to check if it is null.

if (subscriptions != null) {
    
}
2
  • I suggest you to use Newtonsoft.Json. It's best Json converting libarary. Commented Sep 8, 2020 at 3:53
  • I already done using newtonsoft. That's why I wanna try system.text.json :) I can confirm that text.json is faster than newtonsoft that's why I wanna learn more about it. Commented Sep 8, 2020 at 4:17

1 Answer 1

2

First of all you should have some classes to deserialize your json into:

    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:

    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:

    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:

    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());
                }
            }
        }
    }
Sign up to request clarification or add additional context in comments.

4 Comments

This might helpful to me in the future. But for now I'm using a Jsondocument. I don't like to use a property. because I only needed a few information.
I've added an example using JsonDocument too, but I think deserializing your Json file into custom objects is much cleaner.
Yeah it's much cleaner. I actually already know Deserializing . that's why I wanna try Jsondocument. Thanks for your solution.
Thanks for the suggestion about IHttpClientFactory. I actually processing API only. I'm gonna try it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.