This commit is contained in:
James Newton-King
2012-08-15 01:06:34 -07:00
12 changed files with 592 additions and 80 deletions
@@ -0,0 +1,184 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !(NET35 || NET20 || PORTABLE)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using File = System.IO.File;
namespace Newtonsoft.Json.Tests.Documentation
{
public class JsonSchemaTests
{
public void IsValidBasic()
{
#region IsValidBasic
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);
// true
#endregion
}
public void IsValidMessages()
{
string schemaJson = @"{
'description': 'A person',
'type': 'object',
'properties':
{
'name': {'type':'string'},
'hobbies': {
'type': 'array',
'items': {'type':'string'}
}
}
}";
#region IsValidMessages
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);
// false
// Invalid type. Expected String but got Null. Line 2, position 21.
// Invalid type. Expected String but got Float. Line 3, position 51.
#endregion
}
public void JsonValidatingReader()
{
string schemaJson = "{}";
#region JsonValidatingReader
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);
#endregion
}
public void LoadJsonSchema()
{
#region LoadJsonSchema
// load from a string
JsonSchema schema1 = JsonSchema.Parse(@"{'type':'object'}");
// load from a file
using (TextReader reader = File.OpenText(@"c:\schema\Person.json"))
{
JsonSchema schema2 = JsonSchema.Read(new JsonTextReader(reader));
// do stuff
}
#endregion
}
public void ManuallyCreateJsonSchema()
{
#region ManuallyCreateJsonSchema
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} }
}
},
};
JObject person = JObject.Parse(@"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
// true
#endregion
Assert.IsTrue(valid);
}
}
}
#endif
@@ -46,11 +46,43 @@ using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using File = System.IO.File;
namespace Newtonsoft.Json.Tests.Documentation
{
public static class File
{
public static StreamReader OpenText(string path)
{
return null;
}
}
public class LinqToJsonTests
{
public void LinqToJsonBasic()
{
#region LinqToJsonBasic
JObject o = JObject.Parse(@"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");
string cpu = (string)o["CPU"];
// Intel
string firstDrive = (string)o["Drives"][0];
// DVD read/writer
IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive
#endregion
}
public void LinqToJsonCreateNormal()
{
#region LinqToJsonCreateNormal
@@ -194,6 +226,65 @@ namespace Newtonsoft.Json.Tests.Documentation
#endregion
}
public void LinqToJsonReadObject()
{
#region LinqToJsonReadObject
using (StreamReader reader = File.OpenText(@"c:\person.json"))
{
JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
// do stuff
}
#endregion
}
public void LinqToJsonSimpleQuerying()
{
#region LinqToJsonSimpleQuerying
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',
'categories': [
'Json.NET',
'CodePlex'
]
},
{
'title': 'LINQ to JSON beta',
'description': 'Annoucing LINQ to JSON',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'categories': [
'Json.NET',
'LINQ'
]
}
]
}
}";
JObject rss = JObject.Parse(json);
string rssTitle = (string)rss["channel"]["title"];
// James Newton-King
string itemTitle = (string)rss["channel"]["item"][0]["title"];
// Json.NET 1.3 + New license + Now on CodePlex
JArray categories = (JArray)rss["channel"]["item"][0]["categories"];
// ["Json.NET", "CodePlex"]
IList<string> categoriesText = categories.Select(c => (string)c).ToList();
// Json.NET
// CodePlex
#endregion
}
public void LinqToJsonQuerying()
{
JObject rss = new JObject();
@@ -882,6 +882,30 @@ namespace Newtonsoft.Json.Tests.Documentation
// Url = http://www.imdb.com/name/nm0385296/
#endregion
}
public void SerializeMultidimensionalArrayExample()
{
string[,] famousCouples = new string[,]
{
{"Adam", "Eve"},
{"Bonnie", "Clyde"},
{"Donald", "Daisy"},
{"Han", "Leia"}
};
string json = JsonConvert.SerializeObject(famousCouples, Formatting.Indented);
// [
// ["Adam", "Eve"],
// ["Bonnie", "Clyde"],
// ["Donald", "Daisy"],
// ["Han", "Leia"]
// ]
string[,] deserialized = JsonConvert.DeserializeObject<string[,]>(json);
Console.WriteLine(deserialized[3, 0] + ", " + deserialized[3, 1]);
// Han, Leia
}
}
}
#endif
@@ -117,6 +117,7 @@
<Compile Include="Converters\StringEnumConverterTests.cs" />
<Compile Include="Converters\VersionConverterTests.cs" />
<Compile Include="Documentation\ConvertingJsonAndXmlTests.cs" />
<Compile Include="Documentation\JsonSchemaTests.cs" />
<Compile Include="Documentation\ReadingAndWritingJsonTests.cs" />
<Compile Include="Documentation\LinqToJsonTests.cs" />
<Compile Include="Documentation\SerializationTests.cs" />
+22 -1
View File
@@ -768,6 +768,27 @@ namespace Newtonsoft.Json.Tests
BenchmarkSerializeMethod(SerializeMethod.JsonNet, s);
}
[Test]
public void ParseJObject()
{
Stopwatch timer = new Stopwatch();
timer.Start();
for (int i = 0; i < 100000; i++)
{
JObject o = JObject.Parse(@"{
""CPU"": ""Intel"",
""Drives"": [
""DVD read/writer"",
""500 gigabyte hard drive""
]
}");
}
timer.Stop();
string linq = timer.Elapsed.TotalSeconds.ToString();
Console.WriteLine(linq);
}
[Test]
public void JObjectToString()
{
@@ -778,7 +799,7 @@ namespace Newtonsoft.Json.Tests
for (int i = 0; i < Iterations; i++)
{
test["dummy"] = new JValue(i);
Encoding.UTF8.GetBytes(test.ToString(Formatting.None));
test.ToString(Formatting.None);
}
return null;
}, "JObject.ToString");