Json.NET - Quick Starts & API Documentation
LINQ to JSON

LINQ to JSON is a programming API for working with JSON objects. The API has been designed with LINQ in mind to enable to quick querying and creation of JSON objects. LINQ to JSON sits under the Newtonsoft.Json.Linq namespace.

### Creating JSON

There are a number of different options when it comes to creating JSON using LINQ to JSON. The first to create objects imperatively. You have total control but it is more verbose than other options.

    JArray array = new JArray();

    JValue text = new JValue("Manual text");

    JValue date = new JValue(new DateTime(2000, 5, 23));

    array.Add(text);

    array.Add(date);

    string json = array.ToString();

    // [

    //   "Manual text",

    //   "\/Date(958996800000+1200)\/"

    // ]

Another option is to create JSON objects declaratively.

    List<Post> posts = GetPosts();

    JObject rss =

      new JObject(

        new JProperty("channel",

          new JObject(

            new JProperty("title", "James Newton-King"),

            new JProperty("link", "http://james.newtonking.com"),

            new JProperty("description", "James Newton-King's blog."),

            new JProperty("item",

              new JArray(

                from p in posts

                orderby p.Title

                select new JObject(

                  new JProperty("title", p.Title),

                  new JProperty("description", p.Description),

                  new JProperty("link", p.Link),

                  new JProperty("category",

                    new JArray(

                      from c in p.Categories

                      select new JValue(c)))))))));

    Console.WriteLine(rss.ToString());

    //{

    //  "channel": {

    //    "title": "James Newton-King",

    //    "link": "http://james.newtonking.com",

    //    "description": "James Newton-King's blog.",

    //    "item": [

    //      {

    //        "title": "Json.NET 1.3 + New license + Now on CodePlex",

    //        "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",

    //        "link": "http://james.newtonking.com/projects/json-net.aspx",

    //        "category": [

    //          "Json.NET",

    //          "CodePlex"

    //        ]

    //      },

    //      {

    //        "title": "LINQ to JSON beta",

    //        "description": "Annoucing LINQ to JSON",

    //        "link": "http://james.newtonking.com/projects/json-net.aspx",

    //        "category": [

    //          "Json.NET",

    //          "LINQ"

    //        ]

    //      }

    //    ]

    //  }

    //}

You can create a JSON object from a non-JSON type using the FromObject method.

    JObject o = JObject.FromObject(new

    {

      channel = new

      {

        title = "James Newton-King",

        link = "http://james.newtonking.com",

        description = "James Newton-King's blog.",

        item =

            from p in posts

            orderby p.Title

            select new

            {

              title = p.Title,

              description = p.Description,

              link = p.Link,

              category = p.Categories

            }

      }

    });

Finally JSON objects can be created from a string use the Parse method.

    string json = @"{

      CPU: 'Intel',

      Drives: [

        'DVD read/writer',

        ""500 gigabyte hard drive""

      ]

    }";

    JObject o = JObject.Parse(json);

### Querying JSON

The properties methods that are the most useful when querying JSON objects are the Children method and the property index.

Children returns all the children of that object. If it is a JObject it will return a collection of properties to work with and if it is a JArray you will get a collection of the array's values.

The property index is used to get a specific child, either by index position for JSON arrays or property name for JSON objects.

    var postTitles =

      from p in rss["channel"]["item"].Children()

      select (string)p["title"];

    foreach (var item in postTitles)

    {

      Console.WriteLine(item);

    }

    //LINQ to JSON beta

    //Json.NET 1.3 + New license + Now on CodePlex

    var categories =

      from c in rss["channel"]["item"].Children()["category"].Values<string>()

      group c by c into g

      orderby g.Count() descending

      select new { Category = g.Key, Count = g.Count() };

    foreach (var c in categories)

    {

      Console.WriteLine(c.Category + " - Count: " + c.Count);

    }

    //Json.NET - Count: 2

    //LINQ - Count: 1

    //CodePlex - Count: 1

LINQ to JSON can also be used to manually convert from JSON to a .NET object.

    public class Shortie

    {

      public string Original { get; set; }

      public string Shortened { get; set; }

      public string Short { get; set; }

      public ShortieException Error { get; set; }

    }

    public class ShortieException

    {

      public int Code { get; set; }

      public string ErrorMessage { get; set; }

    }

Manually serializing and deserializing between .NET objects is most useful when working with JSON that doesn't closely match your .NET objects.

    string jsonText = @"{

      ""short"":{

        ""original"":""http://www.foo.com/"",

        ""short"":""krehqk"",

        ""error"":{

          ""code"":0,

          ""msg"":""No action taken""}

    }";

    JObject json = JObject.Parse(jsonText);

    Shortie shortie = new Shortie

                      {

                        Original = (string)json["short"]["original"],

                        Short = (string)json["short"]["short"],

                        Error = new ShortieException

                                {

                                  Code = (int)json["short"]["error"]["code"],

                                  ErrorMessage = (string)json["short"]["error"]["msg"]

                                }

                      };

    Console.WriteLine(shortie.Original);

    // http://www.foo.com/

    Console.WriteLine(shortie.Error.ErrorMessage);

    // No action taken