0

I have a byte array and need to convert that to a list of an object. Say the byte array has this

[{name:'ABC',DOB:'01-01-2020'},{name:'XYZ',DOB:'01-03-2020'}]

I have a class

public class sample{
public string name {get; set;}
public DateTime DOB {get; set;}
}

I need to get the data from the byte array as a list of the class sample List<Sample> How can I achieve this?

Sarath
  • 41
  • 4
  • 2
    I see no byte array here, more like some mangled json. Are you saying that text `[{name:'ABC',DOB:'01-01-2020'},{name:'XYZ',DOB:'01-03-2020'}]` is actually an array of byte in textual representation just for this example? or are you confused what a byte array actually is – TheGeneral Mar 02 '21 at 08:41
  • The byte array is from an API call. When the API call is done through browser this is the JSON I get. Added that as an example. – Sarath Mar 02 '21 at 08:43
  • Does this answer your question? [How to convert byte array to any type](https://stackoverflow.com/questions/33022660/how-to-convert-byte-array-to-any-type) – Peter Csala Mar 02 '21 at 08:44
  • Show how you are calling the webapi... minimally, this is likely an easy fix if you are using HttpClient – TheGeneral Mar 02 '21 at 08:44
  • The API call is a URL - http://baseURL/api/controller/parameter1/parameter2 It returns a ByteSyncArray – Sarath Mar 02 '21 at 08:47
  • Are you using HttpClient to call this? – TheGeneral Mar 02 '21 at 08:48
  • Yes. I am using HttpClient – Sarath Mar 02 '21 at 08:51

2 Answers2

0

you can use this code

List<Sample> sampleList = JsonConverter.DeserializeObject<List<Sample>>(json)
Meysam Asadi
  • 6,438
  • 3
  • 7
  • 17
0

Read the stream, pass the stream to the Text.Json DeserializeAsync for a minimally allocated lifestyle.

using var response = await client
   .GetAsync(new Uri("blahblahblahy"));

response.EnsureSuccessStatusCode();

await using var contentStream = await response
   .Content
   .ReadAsStreamAsync();

var result = await JsonSerializer.
   DeserializeAsync<Sample>(contentStream);

Note : Technically (in most cases) you don't need to use the using statements here, However there are certain cases you do, so my advice is just do it

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • Thanks. If I were to get a JSON string as the input, then can I use the same logic to get List ? – Sarath Mar 02 '21 at 10:10