Deserialize MemoryStream to Json C#.Net

How to convert or deserialize memorystream to Json string using C#.Net step by step guide. A simple code example to convert stream to Json object.
In today's article I will show a simple tutorial with example using c#.net how we can convert the MemoryStream to Json string using c#.net. This tutorial example we can use in asp.net core mvc, console application and in windows application. 

So, for this article first we will create a console application and add class file into it. In this class file we will add few properties of employee. 

 public class EmployeeModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Email { get; set; }
} 
First, convert the list into Json string by using JsonSerializer.Serialize(object). After converting or serializing the list object into Json string we will convert this Json string to MempryStream to perform the current tutorial. 
 private MemoryStream ConvertListToMemoryStream()
{
    List<EmployeeModel> employees = new List<EmployeeModel>() {
     new EmployeeModel { Id=1,Name="John" ,Address="Address1",Email="john@mail.com"},
     new EmployeeModel { Id=2,Name="Mate" ,Address="Address1",Email="mate@mail.com"},
     new EmployeeModel { Id=3,Name="Rose" ,Address="Address1",Email="rose@mail.com"},
     new EmployeeModel { Id=4,Name="Pape" ,Address="Address1",Email="pape@mail.com"}
};
    var jsonValue = JsonSerializer.Serialize(employees);
    byte[] byteArray = Encoding.UTF8.GetBytes(jsonValue);
    var memoryStreamData = new MemoryStream(byteArray);
    return memoryStreamData;
} 
In above code i have created a method this method we will use to convert the list object Json and after taht it have been converted to MemoryStream. The value returned by this method we will use to demonstrate how we can convert the MemoryStream to Json String C#. Now lets check the code to convert the MemoryStream to Json String C#.net. 
 var memoryStreamData= ConvertListToMemoryStream()
 var jsonData = Encoding.ASCII.GetString(memoryStreamData.ToArray());
 Console.WriteLine(jsonData); 
In above code first i have prepared the memory stream with the help of created method names as ConvertListToMemoryStream(). After getting the memorystream i have used Encoding.ASCII.GetString(memoryStreamData.ToArray()) to convert the memory stream object again back to string Json format. Now we have done let's run the code and check the output. 

Json Data
Now let's check the complete data in text visualizer.

Json Complete data

Here we can see the complete data available into the list.  Now press F5 to check the final output.

MemeoryStream to Json in C#.net

Post a Comment