20

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"}
]
Yurii
  • 4,811
  • 7
  • 32
  • 41
Chin
  • 12,582
  • 38
  • 102
  • 152
  • possible duplicate of [How to create JSON string in C#](http://stackoverflow.com/questions/1056121/how-to-create-json-string-in-c-sharp) – nawfal Jun 15 '15 at 09:25

4 Answers4

31

in C#:

var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string json = jsonSerializer.Serialize(yourCustomObject);
Brian
  • 4,974
  • 2
  • 28
  • 30
  • 1
    `JavaScriptSerializer` is a pain to use. You should give a try to [Json.Net](http://james.newtonking.com/json) – Falanwe Sep 11 '14 at 06:24
  • 1
    Add **System.Web.Extensions** into References see [https://msdn.microsoft.com/fr-fr/library/system.web.script.serialization.javascriptserializer%28v=vs.110%29.aspx] – themadmax Sep 20 '16 at 12:51
14

I recommand using Json.NET. It's not part of .Net's the core libraries, but it is very widely used, including by a lot of Microsoft's products. Also it's the single most used nuget package. And it's both easier to use than JavaScriptSerializer and more efficient.

var jsonString = JsonConvert.SerializeObject(someObjet);

var myObject = JsonConvert.DeserializeObject<MyType>(jsonString);
Falanwe
  • 4,636
  • 22
  • 37
3

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);
}
Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
3

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

Rohan West
  • 9,262
  • 3
  • 37
  • 64