ToJson() and FromJson<T>()

using System;
using System.Web.Script.Serialization;

namespace Extensions {

    public static class Json {

        public static string ToJson(this object obj) {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        public static string ToJson(this object obj, int recursionDepth) {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recursionDepth;
            return serializer.Serialize(obj);
        }

        public static T FromJson<T>(this object obj) {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Deserialize<T>(obj as string);
        }
    }
}
Example:
Employee emp = new Employee("Dummy", 5000);
string s = emp.ToJson();
emp = null;
emp = s.FromJson<Employee>();

Description

Convert an object to JSON an back

Details

Double click on the code to select all.

 

;