Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# code to serialize plain-old-CLR-objects to JSON

Within an ASP.NET application, I'd like to serialize a collection of plain-old-CLR-objects (POCO) to a JSON string, which will then be sent down to the client as part of a web response.

Is there a light-weight C# library that does this?

like image 783
Jonathan Avatar asked Sep 29 '09 03:09

Jonathan


2 Answers

Yes, I've had a lot of success with JSON.NET.

As an example from the web page:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
like image 88
Jon Skeet Avatar answered Nov 03 '22 11:11

Jon Skeet


Try DataContractJsonSerializer:

Serializes objects to the JavaScript Object Notation (JSON) and deserializes JSON data to objects.

Use the DataContractJsonSerializer class to serialize instances of a type into a JSON document and to deserialize a JSON document into an instance of a type. For example, you can create a type named Person with properties that contain essential data, such as a name and address. You can then create and manipulate an instance of the Person class and write all of its property values in a JSON document for later retrieval. This JSON document can later be deserialized into the Person class or another class with an equivalent data contract.

like image 24
Andrew Hare Avatar answered Nov 03 '22 12:11

Andrew Hare