JSON Serialization using DataContract Serializer

Serialze object to JSON string using DataContractSerializer and Extention Method



 

using System;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Json;
public static class JSONHelper
{
public static string ToJOSN(this T obj)
{
using (MemoryStream ms = new MemoryStream())
{
var ser = new DataContractJsonSerializer(obj.GetType());
ser.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
public static T FromJSON(this string str)
{
using (var ms = new MemoryStream(Encoding.Default.GetBytes(str.ToCharArray())))
{
var ser = new DataContractJsonSerializer(typeof(T));
return (T)ser.ReadObject(ms);
}
}
}



To use DataContractSerializer, we need to mark class which we want to serialize as DataContract.

Let say,

 

[DataContract]
public class student
{
[DataMember(Order=0,IsRequired=true)]
public int rollno { get; set; }
[DataMember(Order=1,IsRequired=true)]
public string name { get; set; }
}


Following is the driving program.

public static void Main(string[] args)
{
var s1 = new student()
{
rollno = 1,
name = "test"
};

// Serialize to Json string
var jsonString = s1.ToJOSN();
// Deserialize to object
var obj = jsonString.FromJSON();
}


Attachments

  • JSONHeler.cs (37599-8713-JSONHelper.cs.txt)
  • Comments

    No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: