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