Serialization:
Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file.
JSON Serialization:
JSON serialization serializes the public properties of an object into a string, byte array, or stream.
public static string SerializeObject(object obj)
{
string jsonString = null;
DataContractJsonSerializer serializer = null;
MemoryStream memorystream = null;
try
{
serializer = new DataContractJsonSerializer(obj.GetType());
memorystream = new MemoryStream();
serializer.WriteObject(memorystream, obj);
jsonString = Encoding.UTF8.GetString(memorystream.ToArray());
}
catch
{
throw;
}
finally
{
if (memorystream != null)
{
memorystream.Close();
memorystream.Dispose();
}
}
return jsonString;
}
JSON Deserialization:
It is used to deserialize a JSON string back to an object.
Below is a generic method that accepts a JSON string and returns an object back.
private static T DeSerializeObject<T>(string jsonString)
{
T obj = default(T);
DataContractJsonSerializer serializer = null;
MemoryStream memorystream = null;
try
{
serializer = new DataContractJsonSerializer(typeof(T));
memorystream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
obj = (T)serializer.ReadObject(memorystream);
}
finally
{
if (memorystream != null)
{
memorystream.Close();
memorystream.Dispose();
}
}
return obj;
}
Comments
Post a Comment