Two simple method for Serialize and Deserialize object to JSON
public static class JSONExtension
{
public static string ToJSON(this object obj )
{
if (obj != null)
{
var json = string.Empty;
var ser = new DataContractJsonSerializer(obj.GetType());
using (var ms = new MemoryStream())
{
ser.WriteObject(ms, obj);
json = Encoding.Default.GetString(ms.ToArray());
}
return json;
}
return null;
}
public static T FromJSON<T>( this string json )
{
if (json == null)
return default(T);
using (var ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(json)))
{
var ser = new DataContractJsonSerializer(typeof(T));
return (T)ser.ReadObject(ms);
}
}
Eg:
var c = new CompetitionModel();
c.Name = "Johan";
c.Result = "22341112";
c.NewsLetter = false;
var jsonString = c.ToJSON();
var compModel = jsonString.FromJSON<CompetitionModel>();
Fork
0 Feedback
You must log in before you can give any feedback
0
Nice! But why not use UTF-8 encoding instead of ASCII?
...
using (var ms = new MemoryStream(**Encoding.UTF8**.GetBytes(json)))
...
1
Ohh... before I did read this I already uploaded the same code, but in different language, F#. Well, now you can compare language differences... (less noise with f#)
http://www.forkcan.com/viewcode/198/Convert-an-object-to-json-and-json-to-object
0
You must log in before you can post a comment


553
1


Mark 'c#' tag as 'like'
Mark 'c#' tag as 'ignore'