0

Can we deserialize a JSON response from Web API to a custom object directly from Stream

The code i am trying is like

var request = new HttpRequestMessage(HttpMethod.Get,
            "https://www.cast.com/api/v1/company");
        request.Headers.Add("Accept", "application/json");
        request.Headers.Add("Auth-Token", "token");

        var client = ClientFactory.CreateClient();

        var response = await client.SendAsync(request);

        if (response.IsSuccessStatusCode)
        {
            using var responseStream = await response.Content.ReadAsStreamAsync();

            var responseData = await JsonSerializer.Deserialize<List<CompanyVM>>(responseStream);   
        }
    

But it is giving build error cannot convert from 'System.IO.Stream' to 'Newtonsoft.Json.JsonReader'

So can we read stream to a string first before deserialize / Can i directly deserialize from Stream

Sebastian
  • 4,625
  • 17
  • 76
  • 145
  • Did you mean to read the Content as a _string_ instead of a _stream_? `ReadAsStringAsync`? – gunr2171 Nov 15 '22 at 17:14
  • 1
    Can we do it without read content to stream . Just to consider this https://www.newtonsoft.com/json/help/html/Performance.htm Reading or writing JSON a piece at a time, instead of having the entire JSON string loaded into memory, is especially important when working with JSON documents greater than 85kb in size to avoid the JSON string ending up in the large object heap. – Sebastian Nov 15 '22 at 17:15
  • Ok, but have you measured a performance impact when reading the content as a string that necessitates deserializing directly from a stream? – gunr2171 Nov 15 '22 at 17:17
  • You can deserialize from a stream as shown in [Can Json.NET serialize / deserialize to / from a stream?](https://stackoverflow.com/questions/8157636/can-json-net-serialize-deserialize-to-from-a-stream), however `JsonSerializer` does not support **`async`** deserialization, so you will need to deserialize synchronously. – dbc Nov 15 '22 at 20:10
  • The problem with the answers on the question that was marked as a 'duplicate' is that it's 11 years old. Much has changed since then. – JoeBrockhaus Nov 16 '22 at 01:34
  • @JoeBrockhaus Yes but dont know how to open it I am also looking for a modern solution. – Sebastian Nov 16 '22 at 09:08
  • You are actually pretty close; you need to pass a `JsonTextReader(StreamReader(Stream))` into the Deserialize method. – JoeBrockhaus Nov 21 '22 at 19:11
  • Another option _(sans Newtonsoft)_ is [`HttpContentExtensions.ReadAsAsync()`](https://learn.microsoft.com/en-us/previous-versions/aspnet/hh835763(v=vs.118)) – JoeBrockhaus Nov 21 '22 at 19:16

0 Answers0