JSON to C# object to JSON

Posted: September 8, 2011 in C#, Javascript, JQuery, JSON
Tags: , , ,

[DataContract]
public class SearchFilter
{
[DataMember]
public string SearchCol { get; set; }
[DataMember]
public string SearchOp { get; set; }
[DataMember]
public string SearchText { get; set; }
[DataMember]
public int PageNo { get; set; }
}
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
public class JSONHelper
{
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
}

public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
}
Usage –

SearchFilter lSearchFilter = JSONHelper.Deserialise<SearchFilter>(“{‘SearchCol’:’Col1′,’SearchOp’:’contains’,’SearchText’:’hi’}”);
lSearchFilter.SearchCol
lSearchFilter.SearchOp

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s