-Samples!

This commit is contained in:
James Newton-King
2013-01-28 23:20:05 +13:00
parent 849f7a9fa8
commit 1c0e2856c2
208 changed files with 713 additions and 693 deletions
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class Clone
{
public void Example()
{
#region Usage
JObject o1 = new JObject
{
{"String", "A string!"},
{"Items", new JArray(1, 2)}
};
Console.WriteLine(o1.ToString());
// {
// "String": "A string!",
// "Items": [
// 1,
// 2
// ]
// }
JObject o2 = (JObject) o1.DeepClone();
Console.WriteLine(o2.ToString());
// {
// "String": "A string!",
// "Items": [
// 1,
// 2
// ]
// }
Console.WriteLine(JToken.DeepEquals(o1, o2));
// true
Console.WriteLine(Object.ReferenceEquals(o1, o2));
// false
#endregion
}
}
}
@@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class CreateJsonAnonymousObject
{
#region Types
public class Post
{
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public IList<string> Categories { get; set; }
}
#endregion
public void Example()
{
#region Usage
List<Post> posts = new List<Post>
{
new Post
{
Title = "Episode VII",
Description = "Episode VII production",
Categories = new List<string>
{
"episode-vii",
"movie"
},
Link = "episode-vii-production.aspx"
}
};
JObject o = JObject.FromObject(new
{
channel = new
{
title = "Star Wars",
link = "http://www.starwars.com",
description = "Star Wars blog.",
item =
from p in posts
orderby p.Title
select new
{
title = p.Title,
description = p.Description,
link = p.Link,
category = p.Categories
}
}
});
Console.WriteLine(o.ToString());
// {
// "channel": {
// "title": "Star Wars",
// "link": "http://www.starwars.com",
// "description": "Star Wars blog.",
// "item": [
// {
// "title": "Episode VII",
// "description": "Episode VII production",
// "link": "episode-vii-production.aspx",
// "category": [
// "episode-vii",
// "movie"
// ]
// }
// ]
// }
// }
#endregion
}
}
}
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class CreateJsonCollectionInitializer
{
public void Example()
{
#region Usage
JObject o = new JObject
{
{"Cpu", "Intel"},
{"Memory", 32},
{
"Drives", new JArray
{
"DVD",
"SSD"
}
}
};
Console.WriteLine(o.ToString());
// {
// "Cpu": "Intel",
// "Memory": 32,
// "Drives": [
// "DVD",
// "SSD"
// ]
// }
#endregion
}
}
}
@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class CreateJsonDeclaratively
{
#region Types
public class Post
{
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public IList<string> Categories { get; set; }
}
#endregion
private List<Post> GetPosts()
{
return null;
}
public void Example()
{
#region Usage
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"
// ]
// }
// ]
// }
// }
#endregion
}
}
}
@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class CreateJsonDynamic
{
public void Example()
{
#region Usage
dynamic product = new JObject();
product.ProductName = "Elbow Grease";
product.Enabled = true;
product.Price = 4.90m;
product.StockCount = 9000;
product.StockValue = 44100;
product.Tags = new JArray("Real", "OnSale");
Console.WriteLine(product.ToString());
// {
// "ProductName": "Elbow Grease",
// "Enabled": true,
// "Price": 4.90,
// "StockCount": 9000,
// "StockValue": 44100,
// "Tags": [
// "Real",
// "OnSale"
// ]
// }
#endregion
}
}
}
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class CreateJsonJTokenWriter
{
public void Example()
{
#region Usage
JTokenWriter writer = new JTokenWriter();
writer.WriteStartObject();
writer.WritePropertyName("name1");
writer.WriteValue("value1");
writer.WritePropertyName("name2");
writer.WriteStartArray();
writer.WriteValue(1);
writer.WriteValue(2);
writer.WriteEndArray();
writer.WriteEndObject();
JObject o = (JObject)writer.Token;
Console.WriteLine(o.ToString());
// {
// "name1": "value1",
// "name2": [
// 1,
// 2
// ]
// }
#endregion
}
}
}
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class CreateJsonManually
{
public void Example()
{
#region Usage
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);
JObject o = new JObject();
o["MyArray"] = array;
string json = o.ToString();
Console.WriteLine(json);
// {
// "MyArray": [
// "Manual text",
// "2000-05-23T00:00:00"
// ]
// }
#endregion
}
}
}
@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class CreateReader
{
public void Example()
{
#region Usage
JObject o = new JObject
{
{"Cpu", "Intel"},
{"Memory", 32},
{
"Drives", new JArray
{
"DVD",
"SSD"
}
}
};
JsonReader reader = o.CreateReader();
while (reader.Read())
{
Console.Write(reader.TokenType);
if (reader.Value != null)
Console.Write(" - " + reader.Value);
Console.WriteLine();
}
// StartObject
// PropertyName - Cpu
// String - Intel
// PropertyName - Memory
// Integer - 32
// PropertyName - Drives
// StartArray
// String - DVD
// String - SSD
// EndArray
// EndObject
#endregion
}
}
}
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class CreateWriter
{
public void Example()
{
#region Usage
JObject o = new JObject
{
{"name1", "value1"},
{"name2", "value2"}
};
JsonWriter writer = o.CreateWriter();
writer.WritePropertyName("name3");
writer.WriteStartArray();
writer.WriteValue(1);
writer.WriteValue(2);
writer.WriteEndArray();
Console.WriteLine(o.ToString());
// {
// "name1": "value1",
// "name2": "value2",
// "name3": [
// 1,
// 2
// ]
// }
#endregion
}
}
}
@@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class DeepEquals
{
public void Example()
{
#region Usage
JValue s1 = new JValue("A string");
JValue s2 = new JValue("A string");
JValue s3 = new JValue("A STRING");
Console.WriteLine(JToken.DeepEquals(s1, s2));
// true
Console.WriteLine(JToken.DeepEquals(s2, s3));
// false
JObject o1 = new JObject
{
{"Integer", 12345},
{"String", "A string"},
{"Items", new JArray(1, 2)}
};
JObject o2 = new JObject
{
{"Integer", 12345},
{"String", "A string"},
{"Items", new JArray(1, 2)}
};
Console.WriteLine(JToken.DeepEquals(o1, o2));
// true
Console.WriteLine(JToken.DeepEquals(s1, o1["String"]));
// true
#endregion
}
}
}
@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class DeserializeWithLinq
{
#region Types
public class BlogPost
{
public string Title { get; set; }
public string AuthorName { get; set; }
public string AuthorTwitter { get; set; }
public string Body { get; set; }
public DateTime PostedDate { get; set; }
}
#endregion
public void Example()
{
#region Usage
string json = @"[
{
'Title': 'Json.NET is awesome!',
'Author': {
'Name': 'James Newton-King',
'Twitter': '@JamesNK',
'Picture': '/jamesnk.png'
},
'Date': '2013-01-23T19:30:00',
'BodyHtml': '&lt;h3&gt;Title!&lt;/h3&gt;\r\n&lt;p&gt;Content!&lt;/p&gt;'
}
]";
JArray blogPostArray = JArray.Parse(json);
IList<BlogPost> blogPosts = blogPostArray.Select(p => new BlogPost
{
Title = (string) p["Title"],
AuthorName = (string) p["Author"]["Name"],
AuthorTwitter = (string) p["Author"]["Twitter"],
PostedDate = (DateTime) p["Date"],
Body = HttpUtility.HtmlDecode((string) p["BodyHtml"])
}).ToList();
Console.WriteLine(blogPosts[0].Body);
// <h3>Title!</h3>
// <p>Content!</p>
#endregion
}
}
}
@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class FromObject
{
#region Types
public class Computer
{
public string Cpu { get; set; }
public int Memory { get; set; }
public IList<string> Drives { get; set; }
}
#endregion
public void Example()
{
#region Usage
JValue i = (JValue)JToken.FromObject(12345);
Console.WriteLine(i.Type);
// Integer
Console.WriteLine(i.ToString());
// 12345
JValue s = (JValue)JToken.FromObject("A string");
Console.WriteLine(s.Type);
// String
Console.WriteLine(s.ToString());
// A string
Computer computer = new Computer
{
Cpu = "Intel",
Memory = 32,
Drives = new List<string>
{
"DVD",
"SSD"
}
};
JObject o = (JObject)JToken.FromObject(computer);
Console.WriteLine(o.ToString());
// {
// "Cpu": "Intel",
// "Memory": 32,
// "Drives": [
// "DVD",
// "SSD"
// ]
// }
JArray a = (JArray)JToken.FromObject(computer.Drives);
Console.WriteLine(a.ToString());
// [
// "DVD",
// "SSD"
// ]
#endregion
}
}
}
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class JObjectProperties
{
public void Example()
{
#region Usage
JObject o = new JObject
{
{ "name1", "value1" },
{ "name2", "value2"}
};
foreach (JProperty property in o.Properties())
{
Console.WriteLine(property.Name + " - " + property.Value);
}
// name1 - value1
// name2 - value2
foreach (KeyValuePair<string, JToken> property in o)
{
Console.WriteLine(property.Key + " - " + property.Value);
}
// name1 - value1
// name2 - value2
#endregion
}
}
}
@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class JValueCast
{
public void Example()
{
#region Usage
JValue v1 = new JValue("1");
int i = (int)v1;
Console.WriteLine(i);
// 1
JValue v2 = new JValue(true);
bool b = (bool)v2;
Console.WriteLine(b);
// true
JValue v3 = new JValue("19.95");
decimal d = (decimal)v3;
Console.WriteLine(d);
// 19.95
JValue v4 = new JValue(new DateTime(2013, 1, 21));
string s = (string)v4;
Console.WriteLine(s);
// 01/21/2013 00:00:00
JValue v5 = new JValue("http://www.bing.com");
Uri u = (Uri)v5;
Console.WriteLine(u);
// http://www.bing.com/
JValue v6 = new JValue((object)null);
u = (Uri)v6;
Console.WriteLine((u != null) ? u.ToString() : "{null}");
// {null}
DateTime? dt = (DateTime?)v6;
Console.WriteLine((dt != null) ? dt.ToString() : "{null}");
// {null}
#endregion
}
}
}
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class JValueValue
{
public void Example()
{
#region Usage
JValue s = new JValue("A string value");
Console.WriteLine(s.Value.GetType().Name);
// String
Console.WriteLine(s.Value);
// A string value
JValue u = new JValue(new Uri("http://www.google.com/"));
Console.WriteLine(u.Value.GetType().Name);
// Uri
Console.WriteLine(u.Value);
// http://www.google.com/
#endregion
}
}
}
@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class ModifyJson
{
public void Example()
{
#region Usage
string json = @"{
'channel': {
'title': 'Star Wars',
'link': 'http://www.starwars.com',
'description': 'Star Wars blog.',
'obsolete': 'Obsolete value',
'item': []
}
}";
JObject rss = JObject.Parse(json);
JObject channel = (JObject)rss["channel"];
channel["title"] = ((string)channel["title"]).ToUpper();
channel["description"] = ((string)channel["description"]).ToUpper();
channel.Property("obsolete").Remove();
channel.Property("description").AddAfterSelf(new JProperty("new", "New value"));
JArray item = (JArray) channel["item"];
item.Add("Item 1");
item.Add("Item 2");
Console.WriteLine(rss.ToString());
// {
// "channel": {
// "title": "STAR WARS",
// "link": "http://www.starwars.com",
// "description": "STAR WARS BLOG.",
// "new": "New value",
// "item": [
// "Item 1",
// "Item 2"
// ]
// }
// }
#endregion
}
}
}
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class ParseJsonAny
{
public void Example()
{
#region Usage
JToken t1 = JToken.Parse("{}");
Console.WriteLine(t1.Type);
// Object
JToken t2 = JToken.Parse("[]");
Console.WriteLine(t2.Type);
// Array
JToken t3 = JToken.Parse("null");
Console.WriteLine(t3.Type);
// Null
JToken t4 = JToken.Parse(@"'A string!'");
Console.WriteLine(t4.Type);
// String
#endregion
}
}
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class ParseJsonArray
{
public void Example()
{
#region Usage
string json = @"[
'Small',
'Medium',
'Large'
]";
JArray a = JArray.Parse(json);
Console.WriteLine(a.ToString());
// [
// "Small",
// "Medium",
// "Large"
// ]
#endregion
}
}
}
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class ParseJsonObject
{
public void Example()
{
#region Usage
string json = @"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
Console.WriteLine(o.ToString());
// {
// "CPU": "Intel",
// "Drives": [
// "DVD read/writer",
// "500 gigabyte hard drive"
// ]
// }
#endregion
}
}
}
@@ -0,0 +1,69 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class QueryJson
{
public void Example()
{
#region Usage
string json = @"{
'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 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'
]
}
]
}
}";
JObject rss = JObject.Parse(json);
string rssTitle = (string)rss["channel"]["title"];
Console.WriteLine(rssTitle);
// James Newton-King
string itemTitle = (string)rss["channel"]["item"][0]["title"];
Console.WriteLine(itemTitle);
// Json.NET 1.3 + New license + Now on CodePlex
JArray categories = (JArray)rss["channel"]["item"][0]["category"];
Console.WriteLine(categories);
// [
// "Json.NET",
// "CodePlex"
// ]
IList<string> categoriesText = categories.Select(c => (string)c).ToList();
Console.WriteLine(string.Join(", ", categoriesText));
// Json.NET, CodePlex
#endregion
}
}
}
@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class QueryJsonDynamic
{
public void Example()
{
#region Usage
string json = @"[
{
'Title': 'Json.NET is awesome!',
'Author': {
'Name': 'James Newton-King',
'Twitter': '@JamesNK',
'Picture': '/jamesnk.png'
},
'Date': '2013-01-23T19:30:00',
'BodyHtml': '&lt;h3&gt;Title!&lt;/h3&gt;\r\n&lt;p&gt;Content!&lt;/p&gt;'
}
]";
dynamic blogPosts = JArray.Parse(json);
dynamic blogPost = blogPosts[0];
string title = blogPost.Title;
Console.WriteLine(title);
// Json.NET is awesome!
string author = blogPost.Author.Name;
Console.WriteLine(author);
// James Newton-King
DateTime postDate = blogPost.Date;
Console.WriteLine(postDate);
// 23/01/2013 7:30:00 p.m.
#endregion
}
}
}
@@ -0,0 +1,71 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class QueryJsonLinq
{
public void Example()
{
#region Usage
string json = @"{
'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 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'
]
}
]
}
}";
JObject rss = JObject.Parse(json);
var postTitles =
from p in rss["channel"]["item"]
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
#endregion
}
}
}
@@ -0,0 +1,62 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class QueryJsonSelectToken
{
public void Example()
{
#region Usage
JObject o = JObject.Parse(@"{
'Stores': [
'Lambton Quay',
'Willis Street'
],
'Manufacturers': [
{
'Name': 'Acme Co',
'Products': [
{
'Name': 'Anvil',
'Price': 50
}
]
},
{
'Name': 'Contoso',
'Products': [
{
'Name': 'Elbow Grease',
'Price': 99.95
},
{
'Name': 'Headlight Fluid',
'Price': 4
}
]
}
]
}");
string name = (string)o.SelectToken("Manufacturers[0].Name");
Console.WriteLine(name);
// Acme Co
decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
Console.WriteLine(productPrice);
// 50
string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
Console.WriteLine(productName);
// Elbow Grease
#endregion
}
}
}
@@ -0,0 +1,63 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class QueryJsonSelectTokenWithLinq
{
public void Example()
{
#region Usage
JObject o = JObject.Parse(@"{
'Stores': [
'Lambton Quay',
'Willis Street'
],
'Manufacturers': [
{
'Name': 'Acme Co',
'Products': [
{
'Name': 'Anvil',
'Price': 50
}
]
},
{
'Name': 'Contoso',
'Products': [
{
'Name': 'Elbow Grease',
'Price': 99.95
},
{
'Name': 'Headlight Fluid',
'Price': 4
}
]
}
]
}");
IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
Console.WriteLine(string.Join(", ", storeNames));
// Lambton Quay, Willis Street
IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name"))
.Where(n => n != null).ToList();
Console.WriteLine(string.Join(", ", firstProductNames));
// Headlight Fluid
decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
Console.WriteLine(totalPrice);
// 149.95
#endregion
}
}
}
@@ -0,0 +1,32 @@
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class ReadJTokenFromBson
{
public void Example()
{
#region Usage
byte[] data = Convert.FromBase64String("KQAAAAJuYW1lMQAHAAAAdmFsdWUxAAJuYW1lMgAHAAAAdmFsdWUyAAA=");
MemoryStream ms = new MemoryStream(data);
JObject o;
using (BsonReader reader = new BsonReader(ms))
{
o = (JObject)JToken.ReadFrom(reader);
}
string value = (string)o["name1"];
Console.WriteLine(value);
// value1
#endregion
}
}
}
@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class ReadJson
{
public void Example()
{
#region Usage
JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));
// read JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject) JToken.ReadFrom(reader);
}
#endregion
}
}
}
@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class SerializeWithLinq
{
#region Types
public class BlogPost
{
public string Title { get; set; }
public string AuthorName { get; set; }
public string AuthorTwitter { get; set; }
public string Body { get; set; }
public DateTime PostedDate { get; set; }
}
#endregion
public void Example()
{
#region Usage
IList<BlogPost> blogPosts = new List<BlogPost>
{
new BlogPost
{
Title = "Json.NET is awesome!",
AuthorName = "James Newton-King",
AuthorTwitter = "JamesNK",
PostedDate = new DateTime(2013, 1, 23, 19, 30, 0),
Body = @"<h3>Title!</h3>
<p>Content!</p>"
}
};
JArray blogPostsArray = new JArray(
blogPosts.Select(p => new JObject
{
{"Title", p.Title},
{
"Author", new JObject
{
{"Name", p.AuthorName},
{"Twitter", p.AuthorTwitter}
}
},
{"Date", p.PostedDate},
{"BodyHtml", HttpUtility.HtmlEncode(p.Body)},
})
);
Console.WriteLine(blogPostsArray.ToString());
// [
// {
// "Title": "Json.NET is awesome!",
// "Author": {
// "Name": "James Newton-King",
// "Twitter": "JamesNK"
// },
// "Date": "2013-01-23T19:30:00",
// "BodyHtml": "&lt;h3&gt;Title!&lt;/h3&gt;\r\n&lt;p&gt;Content!&lt;/p&gt;"
// }
// ]
#endregion
}
}
}
@@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class ToObjectComplex
{
#region Types
public class Person
{
public string Name { get; set; }
}
#endregion
public void Example()
{
#region Usage
string json = @"{
'd': [
{
'Name': 'John Smith'
},
{
'Name': 'Mike Smith'
}
]
}";
JObject o = JObject.Parse(json);
JArray a = (JArray)o["d"];
IList<Person> person = a.ToObject<IList<Person>>();
Console.WriteLine(person[0].Name);
// John Smith
Console.WriteLine(person[1].Name);
// Mike Smith
#endregion
}
}
}
@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class ToObjectGeneric
{
public void Example()
{
#region Usage
JValue v1 = new JValue(true);
bool b = v1.ToObject<bool>();
Console.WriteLine(b);
// true
int i = v1.ToObject<int>();
Console.WriteLine(i);
// 1
string s = v1.ToObject<string>();
Console.WriteLine(s);
// "True"
#endregion
}
}
}
@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class ToObjectType
{
public void Example()
{
#region Usage
JValue v1 = new JValue(true);
bool b = (bool)v1.ToObject(typeof(bool));
Console.WriteLine(b);
// true
int i = (int)v1.ToObject(typeof(int));
Console.WriteLine(i);
// 1
string s = (string)v1.ToObject(typeof(string));
Console.WriteLine(s);
// "True"
#endregion
}
}
}
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class ToString
{
public void Example()
{
#region Usage
JObject o = JObject.Parse(@"{'string1':'value','integer2':99,'datetime3':'2000-05-23T00:00:00'}");
Console.WriteLine(o.ToString());
// {
// "string1": "value",
// "integer2": 99,
// "datetime3": "2000-05-23T00:00:00"
// }
Console.WriteLine(o.ToString(Formatting.None));
// {"string1":"value","integer2":99,"datetime3":"2000-05-23T00:00:00"}
Console.WriteLine(o.ToString(Formatting.None, new JavaScriptDateTimeConverter()));
// {"string1":"value","integer2":99,"datetime3":new Date(959032800000)}
#endregion
}
}
}
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class ToStringJsonConverter
{
public void Example()
{
#region Usage
JObject o = JObject.Parse(@"{'string1':'value','integer2':99,'datetime3':'2000-05-23T00:00:00'}");
Console.WriteLine(o.ToString(Formatting.None, new JavaScriptDateTimeConverter()));
// {"string1":"value","integer2":99,"datetime3":new Date(959032800000)}
#endregion
}
}
}
@@ -0,0 +1,35 @@
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class WriteJTokenToBson
{
public void Example()
{
#region Usage
JObject o = new JObject
{
{"name1","value1"},
{"name2","value2"}
};
MemoryStream ms = new MemoryStream();
using (BsonWriter writer = new BsonWriter(ms))
{
o.WriteTo(writer);
}
string data = Convert.ToBase64String(ms.ToArray());
Console.WriteLine(data);
// KQAAAAJuYW1lMQAHAAAAdmFsdWUxAAJuYW1lMgAHAAAAdmFsdWUyAAA=
#endregion
}
}
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq
{
public class WriteToJsonFile
{
public void Example()
{
#region Usage
JObject videogameRatings = new JObject(
new JProperty("Halo", 9),
new JProperty("Starcraft", 9),
new JProperty("Call of Duty", 7.5));
File.WriteAllText(@"c:\videogames.json", videogameRatings.ToString());
// write JSON directly to a file
using (StreamWriter file = File.CreateText(@"c:\videogames.json"))
using (JsonTextWriter writer = new JsonTextWriter(file))
{
videogameRatings.WriteTo(writer);
}
#endregion
}
}
}