Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode object to JSON

Tags:

json

c#

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"}
]
like image 940
Chin Avatar asked Feb 18 '10 09:02

Chin


2 Answers

in C#:

var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string json = jsonSerializer.Serialize(yourCustomObject);
like image 97
used2could Avatar answered Oct 08 '22 06:10

used2could


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);
like image 43
Falanwe Avatar answered Oct 08 '22 05:10

Falanwe