ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ToJson() and FromJson<T>()

Convert an object to JSON an back

Source

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>();

Author: Unknown

Submitted on: 24 jan. 2008

Language: C#

Type: System.Object

Views: 18795