Click or drag to resize
Json.NETSerializing to JSON with LINQ
 

This sample uses LINQ to JSON to manually convert a .NET type to JSON.

Sample
Types
1public class BlogPost
2{
3    public string Title { get; set; }
4    public string AuthorName { get; set; }
5    public string AuthorTwitter { get; set; }
6    public string Body { get; set; }
7    public DateTime PostedDate { get; set; }
8}
Usage
 1IList<BlogPost> blogPosts = new List<BlogPost>
 2{
 3    new BlogPost
 4    {
 5        Title = "Json.NET is awesome!",
 6        AuthorName = "James Newton-King",
 7        AuthorTwitter = "JamesNK",
 8        PostedDate = new DateTime(2013, 1, 23, 19, 30, 0),
 9        Body = @"<h3>Title!</h3>
10                 <p>Content!</p>"
11    }
12};
13
14JArray blogPostsArray = new JArray(
15    blogPosts.Select(p => new JObject
16    {
17        { "Title", p.Title },
18        {
19            "Author", new JObject
20            {
21                { "Name", p.AuthorName },
22                { "Twitter", p.AuthorTwitter }
23            }
24        },
25        { "Date", p.PostedDate },
26        { "BodyHtml", HttpUtility.HtmlEncode(p.Body) },
27    })
28    );
29
30Console.WriteLine(blogPostsArray.ToString());
31// [
32//   {
33//     "Title": "Json.NET is awesome!",
34//     "Author": {
35//       "Name": "James Newton-King",
36//       "Twitter": "JamesNK"
37//     },
38//     "Date": "2013-01-23T19:30:00",
39//     "BodyHtml": "&lt;h3&gt;Title!&lt;/h3&gt;\r\n&lt;p&gt;Content!&lt;/p&gt;"
40//   }
41// ]