Encode object to JSON

Viewed 62540

Hoping I don't have to reinvent the wheel here but does anyone know if there is a class in C# similar to the one supplied by Adobe for AS3 to convert a generic object to a JSON string?

For example, when I encode an array of objects.

new JSONEncoder(arr).getString();

Output:

[
    {"type":"mobile","number":"02-8988-5566"},
    {"type":"mobile","number":"02-8988-5566"}
]
4 Answers

in C#:

var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string json = jsonSerializer.Serialize(yourCustomObject);

The following methods work well for me (using the JavaScriptSerializer):

public static T FromJson<T>(string input)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    return serializer.Deserialize<T>(input);
}

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

Check this out DataContractJsonSerializer.

Use the DataContractJsonSerializer to serialize and deserialize data in the JavaScript Object Notation (JSON) format. This serialization engine converts JSON data into instances of .NET Framework types and back into JSON data

Related