-Examples

This commit is contained in:
James Newton-King
2013-01-24 17:33:16 +13:00
parent 68eacc480b
commit 290e7543af
31 changed files with 1356 additions and 35 deletions
@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Examples
{
public class ConvertJsonToXml
{
public void Example()
{
string json = @"{
""@Id"": 1,
""Email"": ""james@example.com"",
""Active"": true,
""CreatedDate"": ""2013-01-20T00:00:00Z"",
""Roles"": [
""User"",
""Admin""
],
""Team"": {
""@Id"": 2,
""Name"": ""Software Developers"",
""Description"": ""Creators of fine software products and services.""
}
}";
XNode node = JsonConvert.DeserializeXNode(json, "Root");
Console.WriteLine(node.ToString());
// <Root Id="1">
// <Email>james@example.com</Email>
// <Active>true</Active>
// <CreatedDate>2013-01-20T00:00:00Z</CreatedDate>
// <Roles>User</Roles>
// <Roles>Admin</Roles>
// <Team Id="2">
// <Name>Software Developers</Name>
// <Description>Creators of fine software products and services.</Description>
// </Team>
// </Root>
}
}
}
@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace Newtonsoft.Json.Tests.Documentation.Examples
{
public class ConvertXmlToJson
{
public void Example()
{
string xml = @"<?xml version='1.0' standalone='no'?>
<root>
<person id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
</person>
<person id='2'>
<name>Louis</name>
<url>http://www.yahoo.com</url>
</person>
</root>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc);
Console.WriteLine(json);
// {
// "?xml": {
// "@version": "1.0",
// "@standalone": "no"
// },
// "root": {
// "person": [
// {
// "@id": "1",
// "name": "Alan",
// "url": "http://www.google.com"
// },
// {
// "@id": "2",
// "name": "Louis",
// "url": "http://www.yahoo.com"
// }
// ]
// }
// }
}
}
}
@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace Newtonsoft.Json.Tests.Documentation.Examples
{
public class ConvertXmlToJsonForceArray
{
public void Example()
{
string xml = @"<person id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role>Admin1</role>
</person>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc);
Console.WriteLine(json);
// {
// "person": {
// "@id": "1",
// "name": "Alan",
// "url": "http://www.google.com",
// "role": "Admin1"
// }
// }
xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role json:Array='true'>Admin</role>
</person>";
doc = new XmlDocument();
doc.LoadXml(xml);
json = JsonConvert.SerializeXmlNode(doc);
Console.WriteLine(json);
// {
// "person": {
// "@id": "1",
// "name": "Alan",
// "url": "http://www.google.com",
// "role": [
// "Admin"
// ]
// }
// }
}
}
}
@@ -0,0 +1,96 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples
{
public class CustomJsonConverter
{
public class KeysJsonConverter : JsonConverter
{
private Type[] _types;
public KeysJsonConverter(params Type[] types)
{
_types = types;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
}
else
{
JObject o = (JObject)t;
IList<string> propertyNames = o.Properties().Select(p => p.Name).ToList();
o.AddFirst(new JProperty("Keys", new JArray(propertyNames)));
o.WriteTo(writer);
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException("This is not necessary because CanRead is false so the type will be deserialized as normal.");
}
public override bool CanRead
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return _types.Any(t => t == objectType);
}
}
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public IList<string> Roles { get; set; }
}
public void Example()
{
Employee employee = new Employee
{
FirstName = "James",
LastName = "Newton-King",
Roles = new List<string>
{
"Admin"
}
};
string json = JsonConvert.SerializeObject(employee, Formatting.Indented, new KeysJsonConverter(typeof(Employee)));
Console.WriteLine(json);
// {
// "Keys": [
// "FirstName",
// "LastName",
// "Roles"
// ],
// "FirstName": "James",
// "LastName": "Newton-King",
// "Roles": [
// "Admin"
// ]
// }
Employee newEmployee = JsonConvert.DeserializeObject<Employee>(json, new KeysJsonConverter(typeof(Employee)));
Console.WriteLine(newEmployee.FirstName);
// James
}
}
}
@@ -0,0 +1,77 @@
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples
{
public class CustomTraceWriter
{
public class NLogTraceWriter : ITraceWriter
{
private static readonly Logger Logger = LogManager.GetLogger("NLogTraceWriter");
public TraceLevel LevelFilter
{
// trace all messages. nlog can handle filtering
get { return TraceLevel.Verbose; }
}
public void Trace(TraceLevel level, string message, Exception ex)
{
LogEventInfo logEvent = new LogEventInfo
{
Message = message,
Level = GetLogLevel(level),
Exception = ex
};
// log Json.NET message to NLog
Logger.Log(logEvent);
}
private LogLevel GetLogLevel(TraceLevel level)
{
switch (level)
{
case TraceLevel.Error:
return LogLevel.Error;
case TraceLevel.Warning:
return LogLevel.Warn;
case TraceLevel.Info:
return LogLevel.Info;
case TraceLevel.Off:
return LogLevel.Off;
default:
return LogLevel.Trace;
}
}
}
public void Example()
{
IList<string> countries = new List<string>
{
"New Zealand",
"Australia",
"Denmark",
"China"
};
string json = JsonConvert.SerializeObject(countries, Formatting.Indented, new JsonSerializerSettings
{
TraceWriter = new NLogTraceWriter()
});
Console.WriteLine(json);
// [
// "New Zealand",
// "Australia",
// "Denmark",
// "China"
// ]
}
}
}
@@ -7,7 +7,7 @@ using File = System.IO.File;
namespace Newtonsoft.Json.Tests.Documentation.Examples
{
public class DeserializeWithJsonSerializerToFile
public class DeserializeWithJsonSerializerFromFile
{
public class Movie
{
@@ -0,0 +1,58 @@
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples
{
public class ErrorHandlingAttribute
{
public class Employee
{
private List<string> _roles;
public string Name { get; set; }
public int Age { get; set; }
public List<string> Roles
{
get
{
if (_roles == null)
throw new Exception("Roles not loaded!");
return _roles;
}
set { _roles = value; }
}
public string Title { get; set; }
[OnError]
internal void OnError(StreamingContext context, ErrorContext errorContext)
{
errorContext.Handled = true;
}
}
public void Example()
{
Employee person = new Employee
{
Name = "George Michael Bluth",
Age = 16,
Roles = null,
Title = "Mister Manager"
};
string json = JsonConvert.SerializeObject(person, Formatting.Indented);
Console.WriteLine(json);
// {
// "Name": "George Michael Bluth",
// "Age": 16,
// "Title": "Mister Manager"
// }
}
}
}
@@ -0,0 +1,67 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class QueryJson
{
public void Example()
{
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 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'
]
}
]
}
}";
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
}
}
}
@@ -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.Examples.Linq
{
public class QueryJsonLinq
{
public void Example()
{
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 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'
]
}
]
}
}";
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
}
}
}
@@ -0,0 +1,60 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class QueryJsonSelectToken
{
public void Example()
{
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
}
}
}
@@ -0,0 +1,60 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Linq
{
public class QueryJsonSelectTokenWithLinq
{
public void Example()
{
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
}
}
}
@@ -0,0 +1,30 @@
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.Examples.Linq
{
public class ReadJTokenFromBson
{
public void Example()
{
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
}
}
}
@@ -0,0 +1,33 @@
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.Examples.Linq
{
public class WriteJTokenToBson
{
public void Example()
{
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=
}
}
}
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples
{
public class ReadJsonWithJsonTextReader
{
public void Example()
{
string json = @"{
'CPU': 'Intel',
'PSU': '500W',
'Drives': [
'DVD read/writer'
/*(broken)*/,
'500 gigabyte hard drive',
'200 gigabype hard drive'
]
}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
while (reader.Read())
{
if (reader.Value != null)
Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
else
Console.WriteLine("Token: {0}", reader.TokenType);
}
// Token: StartObject
// Token: PropertyName, Value: CPU
// Token: String, Value: Intel
// Token: PropertyName, Value: PSU
// Token: String, Value: 500W
// Token: PropertyName, Value: Drives
// Token: StartArray
// Token: String, Value: DVD read/writer
// Token: Comment, Value: (broken)
// Token: String, Value: 500 gigabyte hard drive
// Token: String, Value: 200 gigabype hard drive
// Token: EndArray
// Token: EndObject
}
}
}
@@ -0,0 +1,57 @@
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema
{
public class CreateJsonSchemaManually
{
public void Example()
{
JsonSchema schema = new JsonSchema();
schema.Type = JsonSchemaType.Object;
schema.Properties = new Dictionary<string, JsonSchema>
{
{"name", new JsonSchema {Type = JsonSchemaType.String}},
{
"hobbies", new JsonSchema
{
Type = JsonSchemaType.Array,
Items = new List<JsonSchema> { new JsonSchema {Type = JsonSchemaType.String} }
}
},
};
string schemaJson = schema.ToString();
Console.WriteLine(schemaJson);
// {
// "type": "object",
// "properties": {
// "name": {
// "type": "string"
// },
// "hobbies": {
// "type": "array",
// "items": {
// "type": "string"
// }
// }
// }
// }
JObject person = JObject.Parse(@"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
Console.WriteLine(valid);
// true
}
}
}
@@ -0,0 +1,39 @@
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema
{
public class JTokenIsValid
{
public void Example()
{
string schemaJson = @"{
'description': 'A person',
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {
'type': 'array',
'items': {'type':'string'}
}
}
}";
JsonSchema schema = JsonSchema.Parse(schemaJson);
JObject person = JObject.Parse(@"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
Console.WriteLine(valid);
// true
}
}
}
@@ -0,0 +1,47 @@
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema
{
public class JTokenIsValidWithMessages
{
public void Example()
{
string schemaJson = @"{
'description': 'A person',
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {
'type': 'array',
'items': {'type':'string'}
}
}
}";
JsonSchema schema = JsonSchema.Parse(schemaJson);
JObject person = JObject.Parse(@"{
'name': null,
'hobbies': ['Invalid content', 0.123456789]
}");
IList<string> messages;
bool valid = person.IsValid(schema, out messages);
Console.WriteLine(valid);
// false
foreach (string message in messages)
{
Console.WriteLine(message);
}
// Invalid type. Expected String but got Null. Line 2, position 21.
// Invalid type. Expected String but got Float. Line 3, position 51.
}
}
}
@@ -0,0 +1,46 @@
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema
{
public class JTokenValidateWithEvent
{
public void Example()
{
string schemaJson = @"{
'description': 'A person',
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {
'type': 'array',
'items': {'type':'string'}
}
}
}";
JsonSchema schema = JsonSchema.Parse(schemaJson);
JObject person = JObject.Parse(@"{
'name': null,
'hobbies': ['Invalid content', 0.123456789]
}");
IList<string> messages = new List<string>();
ValidationEventHandler validationEventHandler = (sender, args) => { messages.Add(args.Message); };
person.Validate(schema, validationEventHandler);
foreach (string message in messages)
{
Console.WriteLine(message);
}
// Invalid type. Expected String but got Null. Line 2, position 21.
// Invalid type. Expected String but got Float. Line 3, position 51.
}
}
}
@@ -0,0 +1,32 @@
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema
{
public class JsonSchemaLoad
{
public void Example()
{
string schemaJson = @"{'type': 'object'}";
JsonSchema schema;
using (TextReader file = File.OpenText(@"c:\schema.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
schema = JsonSchema.Read(reader);
}
JObject o = JObject.Parse(@"{}");
bool valid = o.IsValid(schema);
Console.WriteLine(valid);
// true
}
}
}
@@ -0,0 +1,39 @@
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema
{
public class JsonSchemaParse
{
public void Example()
{
string schemaJson = @"{
'description': 'A person',
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {
'type': 'array',
'items': {'type':'string'}
}
}
}";
JsonSchema schema = JsonSchema.Parse(schemaJson);
Console.WriteLine(schema.Type);
// Object
foreach (var property in schema.Properties)
{
Console.WriteLine(property.Key + " - " + property.Value.Type);
}
// name - String
// hobbies - Array
}
}
}
@@ -0,0 +1,57 @@
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema
{
public class JsonValidatingReaderAndSerializer
{
public class Person
{
public string Name { get; set; }
public IList<string> Hobbies { get; set; }
}
public void Example()
{
string schemaJson = @"{
'description': 'A person',
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {
'type': 'array',
'items': {'type':'string'}
}
}
}";
string json = @"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
JsonValidatingReader validatingReader = new JsonValidatingReader(reader);
validatingReader.Schema = JsonSchema.Parse(schemaJson);
IList<string> messages = new List<string>();
validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message);
JsonSerializer serializer = new JsonSerializer();
Person p = serializer.Deserialize<Person>(validatingReader);
Console.WriteLine(p.Name);
// James
bool isValid = (messages.Count == 0);
Console.WriteLine(isValid);
// true
}
}
}
@@ -0,0 +1,25 @@
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema
{
public class LoadJsonSchemaFromFile
{
public void Example()
{
// read file into a string and parse JsonSchema from the string
JsonSchema schema1 = JsonSchema.Parse(File.ReadAllText(@"c:\schema.json"));
// read JsonSchema directly from a file
using (StreamReader file = File.OpenText(@"c:\schema.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JsonSchema schema2 = JsonSchema.Read(reader);
}
}
}
}
@@ -0,0 +1,55 @@
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema
{
public class RefJsonSchemaResolver
{
public void Example()
{
string schemaJson;
JsonSchemaResolver resolver = new JsonSchemaResolver();
schemaJson = @"{
""id"": ""person"",
""type"": ""object"",
""properties"": {
""name"": {""type"":""string""},
""age"": {""type"":""integer""}
}
}";
JsonSchema personSchema = JsonSchema.Parse(schemaJson, resolver);
schemaJson = @"{
""id"": ""employee"",
""type"": ""object"",
""extends"": {""$ref"":""person""},
""properties"": {
""salary"": {""type"":""number""},
""jobTitle"": {""type"":""string""}
}
}";
JsonSchema employeeSchema = JsonSchema.Parse(schemaJson, resolver);
string json = @"{
""name"": ""James"",
""age"": 29,
""salary"": 9000.01,
""jobTitle"": ""Junior Vice President""
}";
JObject employee = JObject.Parse(json);
bool valid = employee.IsValid(employeeSchema);
Console.WriteLine(valid);
// true
}
}
}
@@ -0,0 +1,27 @@
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples.Schema
{
public class SaveJsonSchemaToFile
{
public void Example()
{
JsonSchema schema = JsonSchema.Parse(@"{'type': 'object'}");
// serialize JsonSchema to a string and then write string to a file
File.WriteAllText(@"c:\schema.json", schema.ToString());
// serialize JsonSchema directly to a file
using (StreamWriter file = File.CreateText(@"c:\schema.json"))
using (JsonTextWriter writer = new JsonTextWriter(file))
{
schema.WriteTo(writer);
}
}
}
}
@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples
{
public class SerializeConditionalProperty
{
public class Employee
{
public string Name { get; set; }
public Employee Manager { get; set; }
public bool ShouldSerializeManager()
{
// don't serialize the Manager property if an employee is their own manager
return (Manager != this);
}
}
public void Example()
{
Employee joe = new Employee();
joe.Name = "Joe Employee";
Employee mike = new Employee();
mike.Name = "Mike Manager";
joe.Manager = mike;
// mike is his own manager
// ShouldSerialize will skip this property
mike.Manager = mike;
string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented);
// [
// {
// "Name": "Joe Employee",
// "Manager": {
// "Name": "Mike Manager"
// }
// },
// {
// "Name": "Mike Manager"
// }
// ]
}
}
}
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Examples
{
public class WriteJsonWithJsonTextWriter
{
public void Example()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartObject();
writer.WritePropertyName("CPU");
writer.WriteValue("Intel");
writer.WritePropertyName("PSU");
writer.WriteValue("500W");
writer.WritePropertyName("Drives");
writer.WriteStartArray();
writer.WriteValue("DVD read/writer");
writer.WriteComment("(broken)");
writer.WriteValue("500 gigabyte hard drive");
writer.WriteValue("200 gigabype hard drive");
writer.WriteEnd();
writer.WriteEndObject();
}
Console.WriteLine(sb.ToString());
// {
// "CPU": "Intel",
// "PSU": "500W",
// "Drives": [
// "DVD read/writer"
// /*(broken)*/,
// "500 gigabyte hard drive",
// "200 gigabype hard drive"
// ]
// }
}
}
}
@@ -306,7 +306,7 @@ namespace Newtonsoft.Json.Tests.Documentation
#region LinqToJsonQuerying
var postTitles =
from p in rss["channel"]["item"].Children()
from p in rss["channel"]["item"]
select (string)p["title"];
foreach (var item in postTitles)
@@ -53,40 +53,40 @@ using System.Globalization;
namespace Newtonsoft.Json.Tests.Documentation
{
public class LogEventInfo
{
public LogLevel Level;
public string Message;
public Exception Exception;
}
public class LogLevel
{
public static LogLevel Info;
public static LogLevel Trace;
public static LogLevel Error;
public static LogLevel Warn;
public static LogLevel Off;
}
public class Logger
{
public void Log(LogEventInfo logEvent)
{
}
}
public static class LogManager
{
public static Logger GetLogger(string className)
{
return new Logger();
}
}
[TestFixture]
public class TraceWriterTests : TestFixtureBase
{
public class LogEventInfo
{
public LogLevel Level;
public string Message;
public Exception Exception;
}
public class LogLevel
{
public static LogLevel Info;
public static LogLevel Trace;
public static LogLevel Error;
public static LogLevel Warn;
public static LogLevel Off;
}
public class Logger
{
public void Log(LogEventInfo logEvent)
{
}
}
public static class LogManager
{
public static Logger GetLogger(string className)
{
return new Logger();
}
}
#region CustomTraceWriterExample
public class NLogTraceWriter : ITraceWriter
{
@@ -45,6 +45,26 @@ namespace Newtonsoft.Json.Tests.Linq
[TestFixture]
public class JArrayTests : TestFixtureBase
{
[Test]
public void RemoveSpecificAndRemoveSelf()
{
JObject o = new JObject
{
{"results", new JArray(1, 2, 3, 4)}
};
JArray a = (JArray)o["results"];
var last = a.Last();
Assert.IsTrue(a.Remove(last));
last = a.Last();
last.Remove();
Assert.AreEqual(2, a.Count);
}
[Test]
public void Clear()
{
@@ -119,9 +119,30 @@
<Compile Include="Converters\VersionConverterTests.cs" />
<Compile Include="Documentation\ConvertingJsonAndXmlTests.cs" />
<Compile Include="Documentation\ConditionalPropertiesTests.cs" />
<Compile Include="Documentation\Examples\ConvertJsonToXml.cs" />
<Compile Include="Documentation\Examples\ConvertXmlToJson.cs" />
<Compile Include="Documentation\Examples\ConvertXmlToJsonForceArray.cs" />
<Compile Include="Documentation\Examples\CustomJsonConverter.cs" />
<Compile Include="Documentation\Examples\CustomTraceWriter.cs" />
<Compile Include="Documentation\Examples\DeserializeFromBson.cs" />
<Compile Include="Documentation\Examples\DeserializeFromBsonCollection.cs" />
<Compile Include="Documentation\Examples\ErrorHandlingAttribute.cs" />
<Compile Include="Documentation\Examples\Linq\QueryJsonLinq.cs" />
<Compile Include="Documentation\Examples\Linq\QueryJson.cs" />
<Compile Include="Documentation\Examples\Linq\QueryJsonSelectTokenWithLinq.cs" />
<Compile Include="Documentation\Examples\Linq\QueryJsonSelectToken.cs" />
<Compile Include="Documentation\Examples\ReadJsonWithJsonTextReader.cs" />
<Compile Include="Documentation\Examples\Schema\JTokenValidateWithEvent.cs" />
<Compile Include="Documentation\Examples\Schema\JTokenIsValidWithMessages.cs" />
<Compile Include="Documentation\Examples\Schema\CreateJsonSchemaManually.cs" />
<Compile Include="Documentation\Examples\Schema\JsonValidatingReaderAndSerializer.cs" />
<Compile Include="Documentation\Examples\Schema\JTokenIsValid.cs" />
<Compile Include="Documentation\Examples\Schema\RefJsonSchemaResolver.cs" />
<Compile Include="Documentation\Examples\Schema\SaveJsonSchemaToFile.cs" />
<Compile Include="Documentation\Examples\Schema\JsonSchemaLoad.cs" />
<Compile Include="Documentation\Examples\Schema\JsonSchemaParse.cs" />
<Compile Include="Documentation\Examples\Linq\Clone.cs" />
<Compile Include="Documentation\Examples\Linq\ReadJTokenFromBson.cs" />
<Compile Include="Documentation\Examples\Linq\CreateJsonDynamic.cs" />
<Compile Include="Documentation\Examples\Linq\QueryJsonDynamic.cs" />
<Compile Include="Documentation\Examples\Linq\SerializeWithLinq.cs" />
@@ -147,8 +168,10 @@
<Compile Include="Documentation\Examples\Linq\ToObjectType.cs" />
<Compile Include="Documentation\Examples\Linq\ToString.cs" />
<Compile Include="Documentation\Examples\Linq\ToStringJsonConverter.cs" />
<Compile Include="Documentation\Examples\Linq\WriteJTokenToBson.cs" />
<Compile Include="Documentation\Examples\Linq\WriteToJsonFile.cs" />
<Compile Include="Documentation\Examples\Linq\ReadJson.cs" />
<Compile Include="Documentation\Examples\Schema\LoadJsonSchemaFromFile.cs" />
<Compile Include="Documentation\Examples\SerializeDictionary.cs" />
<Compile Include="Documentation\Examples\CustomContractResolver.cs" />
<Compile Include="Documentation\Examples\DataContractAndDataMember.cs" />
@@ -157,7 +180,7 @@
<Compile Include="Documentation\Examples\DeserializeAnonymousType.cs" />
<Compile Include="Documentation\Examples\DeserializeConstructorHandling.cs" />
<Compile Include="Documentation\Examples\DeserializeMissingMemberHandling.cs" />
<Compile Include="Documentation\Examples\DeserializeWithJsonSerializerToFile.cs" />
<Compile Include="Documentation\Examples\DeserializeWithJsonSerializerFromFile.cs" />
<Compile Include="Documentation\Examples\DeserializeCollection.cs" />
<Compile Include="Documentation\Examples\DeserializeDictionary.cs" />
<Compile Include="Documentation\Examples\DeserializeObject.cs" />
@@ -189,6 +212,7 @@
<Compile Include="Documentation\Examples\SerializeWithJsonConverters.cs" />
<Compile Include="Documentation\Examples\SerializeWithJsonSerializerToFile.cs" />
<Compile Include="Documentation\Examples\TraceWriter.cs" />
<Compile Include="Documentation\Examples\WriteJsonWithJsonTextWriter.cs" />
<Compile Include="Documentation\TraceWriterTests.cs" />
<Compile Include="Documentation\JsonNetVsWindowsDataJsonTests.cs" />
<Compile Include="Documentation\PerformanceTests.cs" />
+1 -1
View File
@@ -35,7 +35,7 @@ using System.Globalization;
namespace Newtonsoft.Json.Bson
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
/// </summary>
public class BsonWriter : JsonWriter
{