2015/07/18

How to serialize / deserialize object to json in C# ?

// Install-Package Newtonsoft.Json
using Newtonsoft.Json;
public static void SerializeJson(this object obj, string filePath)
{
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.WriteLine(json);
}
}
public static T DeserializeJson<T>(this T obj, string jsonFilePath)
{
string json = null;
using (StreamReader sr = new StreamReader(jsonFilePath))
{
json = sr.ReadToEnd();
}
return JsonConvert.DeserializeObject<T>(json);
}
view raw gistfile1.cs hosted with ❤ by GitHub

No comments:

Post a Comment