Cheung
Cheung

Reputation: 15552

Does .NET 4 have a built-in JSON serializer/deserializer?

Does .NET 4 come with any class that serializes/deserializes JSON data?

Upvotes: 74

Views: 93057

Answers (4)

vinsa
vinsa

Reputation: 1242

Use this generic class in order to serialize / deserialize JSON. You can easy serialize complex data structure like this:

Dictionary<string, Tuple<int, int[], bool, string>>

to JSON string and then to save it in application setting or else

public class JsonSerializer
{
    public string Serialize<T>(T Obj)
    {
        using (var ms = new MemoryStream())
        {
            DataContractJsonSerializer serialiser = new DataContractJsonSerializer(typeof(T));
            serialiser.WriteObject(ms, Obj);
            byte[] json = ms.ToArray();
            return Encoding.UTF8.GetString(json, 0, json.Length);
        }
    }

    public T Deserialize<T>(string Json)
    {
        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(Json)))
        {
            DataContractJsonSerializer serialiser = new DataContractJsonSerializer(typeof(T));
            var deserializedObj = (T)serialiser.ReadObject(ms);
            return deserializedObj;
        }
    }
}

Upvotes: 14

Zane
Zane

Reputation: 1

.NET4 has a built-in JSON Class,such as DataContractJsonSerializer ,but it is very weak,it doesn't support multidimentional array. I suggest you use JSON.Net

Upvotes: 0

Coding Flow
Coding Flow

Reputation: 21881

You can use the DataContractJsonSerializer class anywhere you want, it is just a .net class and is not limited to WCF. More info on how to use it here and here.

Upvotes: 44

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

There's the JavaScriptSerializer class (although you will need to reference the System.Web.Extensions assembly the class works perfectly fine in WinForms/WPF applications). Also even if the DataContractJsonSerializer class was designed for WCF it works fine in client applications.

Upvotes: 31

Related Questions