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

Posted By

Adam Nagy

Follow @AdamTheNagy Adam Nagy joined Autodesk back in 2005 and has been providing programming support, consulting, training and evangelism to external developers. He started his career in Budapest, then worked in Prague for 3 years and now lives in South England, UK. At the moment focusing on Inventor and Fusion 360, plus cloud and mobile related technologies. Adam has a degree in Software Engineering and has...