serializes a List of strings using a MemoryStream, prints out JSON, deserializes List in order to print out its contents. - CSharp File IO

CSharp examples for File IO:Serialization

Description

serializes a List of strings using a MemoryStream, prints out JSON, deserializes List in order to print out its contents.

Demo Code

using System;/*  ww  w  .j a  v a2s . com*/
using System.Collections.Generic;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
class MainClass
{
   public static void Main()
   {
      List<string> myList = new List<string>()
      {
         "apple", "orange", "banana", "cherry"
      };
      MemoryStream memoryStream = new MemoryStream();
      DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(myList.GetType());
      jsonSerializer.WriteObject(memoryStream, myList);
      string jsonString = Encoding.Default.GetString(memoryStream.ToArray());
      Console.WriteLine(jsonString);
      memoryStream = new MemoryStream(Encoding.Default.GetBytes(jsonString));
      myList = jsonSerializer.ReadObject(memoryStream) as List<string>;
      foreach (string strValue in myList){
         Console.WriteLine(strValue);
      }
   }
}

Result


Related Tutorials