Setting values and creating objects and arrays one at a time gives you total control but it is more verbose than other options.
Creating JSON Copy imageCopy
1JArray array = new JArray();
2JValue text = new JValue("Manual text");
3JValue date = new JValue(new DateTime(2000, 5, 23));
4
5array.Add(text);
6array.Add(date);
7
8string json = array.ToString();
9// [
10// "Manual text",
11// "2000-05-23T00:00:00"
12// ]
Creating JSON with LINQ
Declaratively creating JSON objects using LINQ is a fast way to create JSON from collections of values.
Creating JSON Declaratively Copy imageCopy
1List<Post> posts = GetPosts();
2
3JObject rss =
4 new JObject(
5 new JProperty("channel",
6 new JObject(
7 new JProperty("title", "James Newton-King"),
8 new JProperty("link", "http://james.newtonking.com"),
9 new JProperty("description", "James Newton-King‘s blog."),
10 new JProperty("item",
11 new JArray(
12 from p in posts
13 orderby p.Title
14 select new JObject(
15 new JProperty("title", p.Title),
16 new JProperty("description", p.Description),
17 new JProperty("link", p.Link),
18 new JProperty("category",
19 new JArray(
20 from c in p.Categories
21 select new JValue(c)))))))));
22
23Console.WriteLine(rss.ToString());
24
25//{
26// "channel": {
27// "title": "James Newton-King",
28// "link": "http://james.newtonking.com",
29// "description": "James Newton-King‘s blog.",
30// "item": [
31// {
32// "title": "Json.NET 1.3 + New license + Now on CodePlex",
33// "description": "Annoucing the release of Json.NET 1.3, the MIT license and being available on CodePlex",
34// "link": "http://james.newtonking.com/projects/json-net.aspx",
35//
Json.NET - Documentation Creating JSON,布布扣,bubuko.com