23 Jan 2023

Handle Model Properties API endpoints in .NET

Default blog image

I think these are the first API endpoints we have where you might get back more than just one JSON object in a single query delimited by newline characters:

As the documentation mentions it in the Response Summary, you can find information about this format here:
https://en.wikipedia.org/wiki/JSON_streaming  

In order to help others handle these endpoints, my colleague Jan Liska provided the code that he has been using:

private async IAsyncEnumerable<T> StreamLineDelimitedJson<T>(string token, string url)
{
    RestRequest request = new(url, Method.Get);
​
    request.AddHeader("Authorization", $"Bearer {token}");
    var stream = await RestClient.DownloadStreamAsync(request).ConfigureAwait(false);
​
    if (stream == null)
    {
        yield break;
    }
    using var reader = new StreamReader(stream);
​
    while (!reader.EndOfStream)
    {
        string? line = await reader.ReadLineAsync().ConfigureAwait(false);
​
        if (string.IsNullOrEmpty(line))
        {
            continue;
        }
        var item = JsonConvert.DeserializeObject<T>(line);
​
        if (item != null)
        {
            yield return item;
        }
    }
}

 

Related Article