初始化

This commit is contained in:
2025-12-11 11:39:02 +08:00
commit 156d6ccb06
1708 changed files with 1162911 additions and 0 deletions

View File

@@ -0,0 +1,32 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Lib", "Lib", "{620042D9-2753-48F5-BEDE-3905248781D2}"
ProjectSection(SolutionItems) = preProject
Lib\NUnit\DotNet\nunit.framework.dll = Lib\NUnit\DotNet\nunit.framework.dll
Lib\NUnit\DotNet\nunit.framework.xml = Lib\NUnit\DotNet\nunit.framework.xml
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Net20", "Newtonsoft.Json\Newtonsoft.Json.Net20.csproj", "{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Tests.Net20", "Newtonsoft.Json.Tests\Newtonsoft.Json.Tests.Net20.csproj", "{3E6E2335-B079-4B5B-A65A-9D586914BCBB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Release|Any CPU.Build.0 = Release|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,26 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Net35", "Newtonsoft.Json\Newtonsoft.Json.Net35.csproj", "{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Tests.Net35", "Newtonsoft.Json.Tests\Newtonsoft.Json.Tests.Net35.csproj", "{3E6E2335-B079-4B5B-A65A-9D586914BCBB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Release|Any CPU.Build.0 = Release|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,32 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Lib", "Lib", "{620042D9-2753-48F5-BEDE-3905248781D2}"
ProjectSection(SolutionItems) = preProject
Lib\NUnit\DotNet\nunit.framework.dll = Lib\NUnit\DotNet\nunit.framework.dll
Lib\NUnit\DotNet\nunit.framework.xml = Lib\NUnit\DotNet\nunit.framework.xml
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Net40", "Newtonsoft.Json\Newtonsoft.Json.Net40.csproj", "{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Tests.Net40", "Newtonsoft.Json.Tests\Newtonsoft.Json.Tests.Net40.csproj", "{3E6E2335-B079-4B5B-A65A-9D586914BCBB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Release|Any CPU.Build.0 = Release|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,34 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30324.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Lib", "Lib", "{620042D9-2753-48F5-BEDE-3905248781D2}"
ProjectSection(SolutionItems) = preProject
Lib\NUnit\DotNet\nunit.framework.dll = Lib\NUnit\DotNet\nunit.framework.dll
Lib\NUnit\DotNet\nunit.framework.xml = Lib\NUnit\DotNet\nunit.framework.xml
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Portable", "Newtonsoft.Json\Newtonsoft.Json.Portable.csproj", "{959F7F85-C98B-4876-971A-9036224578E4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Tests.Portable", "Newtonsoft.Json.Tests\Newtonsoft.Json.Tests.Portable.csproj", "{3E6E2335-B079-4B5B-A65A-9D586914BCBB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{959F7F85-C98B-4876-971A-9036224578E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{959F7F85-C98B-4876-971A-9036224578E4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{959F7F85-C98B-4876-971A-9036224578E4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{959F7F85-C98B-4876-971A-9036224578E4}.Release|Any CPU.Build.0 = Release|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,34 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Lib", "Lib", "{620042D9-2753-48F5-BEDE-3905248781D2}"
ProjectSection(SolutionItems) = preProject
Lib\NUnit\DotNet\nunit.framework.dll = Lib\NUnit\DotNet\nunit.framework.dll
Lib\NUnit\DotNet\nunit.framework.xml = Lib\NUnit\DotNet\nunit.framework.xml
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Portable40", "Newtonsoft.Json\Newtonsoft.Json.Portable40.csproj", "{959F7F85-C98B-4876-971A-9036224578E4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Tests.Portable40", "Newtonsoft.Json.Tests\Newtonsoft.Json.Tests.Portable40.csproj", "{3E6E2335-B079-4B5B-A65A-9D586914BCBB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{959F7F85-C98B-4876-971A-9036224578E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{959F7F85-C98B-4876-971A-9036224578E4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{959F7F85-C98B-4876-971A-9036224578E4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{959F7F85-C98B-4876-971A-9036224578E4}.Release|Any CPU.Build.0 = Release|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,856 @@
#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
using System;
using System.Collections.Generic;
#if !(NET20 || NET35 || PORTABLE)
using System.Numerics;
#endif
using System.Text;
using System.Text.RegularExpressions;
#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.Bson;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Tests.TestObjects;
using System.Globalization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Tests.Bson
{
[TestFixture]
public class BsonWriterTests : TestFixtureBase
{
[Test]
public void CloseOutput()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
Assert.IsTrue(ms.CanRead);
writer.Close();
Assert.IsFalse(ms.CanRead);
ms = new MemoryStream();
writer = new BsonWriter(ms) { CloseOutput = false };
Assert.IsTrue(ms.CanRead);
writer.Close();
Assert.IsTrue(ms.CanRead);
}
[Test]
public void WriteSingleObject()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartObject();
writer.WritePropertyName("Blah");
writer.WriteValue(1);
writer.WriteEndObject();
string bson = BytesToHex(ms.ToArray());
Assert.AreEqual("0F-00-00-00-10-42-6C-61-68-00-01-00-00-00-00", bson);
}
#if !NET20
[Test]
public void WriteValues()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartArray();
writer.WriteValue(long.MaxValue);
writer.WriteValue((ulong)long.MaxValue);
writer.WriteValue(int.MaxValue);
writer.WriteValue((uint)int.MaxValue);
writer.WriteValue(byte.MaxValue);
writer.WriteValue(sbyte.MaxValue);
writer.WriteValue('a');
writer.WriteValue(decimal.MaxValue);
writer.WriteValue(double.MaxValue);
writer.WriteValue(float.MaxValue);
writer.WriteValue(true);
writer.WriteValue(new byte[] { 0, 1, 2, 3, 4 });
writer.WriteValue(new DateTimeOffset(2000, 12, 29, 12, 30, 0, TimeSpan.Zero));
writer.WriteValue(new DateTime(2000, 12, 29, 12, 30, 0, DateTimeKind.Utc));
writer.WriteEnd();
string bson = BytesToHex(ms.ToArray());
Assert.AreEqual("8C-00-00-00-12-30-00-FF-FF-FF-FF-FF-FF-FF-7F-12-31-00-FF-FF-FF-FF-FF-FF-FF-7F-10-32-00-FF-FF-FF-7F-10-33-00-FF-FF-FF-7F-10-34-00-FF-00-00-00-10-35-00-7F-00-00-00-02-36-00-02-00-00-00-61-00-01-37-00-00-00-00-00-00-00-F0-45-01-38-00-FF-FF-FF-FF-FF-FF-EF-7F-01-39-00-00-00-00-E0-FF-FF-EF-47-08-31-30-00-01-05-31-31-00-05-00-00-00-00-00-01-02-03-04-09-31-32-00-40-C5-E2-BA-E3-00-00-00-09-31-33-00-40-C5-E2-BA-E3-00-00-00-00", bson);
}
#endif
[Test]
public void WriteDouble()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartArray();
writer.WriteValue(99.99d);
writer.WriteEnd();
string bson = BytesToHex(ms.ToArray());
Assert.AreEqual("10-00-00-00-01-30-00-8F-C2-F5-28-5C-FF-58-40-00", bson);
}
[Test]
public void WriteGuid()
{
Guid g = new Guid("D821EED7-4B5C-43C9-8AC2-6928E579B705");
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartArray();
writer.WriteValue(g);
writer.WriteEnd();
string bson = BytesToHex(ms.ToArray());
Console.WriteLine(bson);
Assert.AreEqual("1D-00-00-00-05-30-00-10-00-00-00-04-D7-EE-21-D8-5C-4B-C9-43-8A-C2-69-28-E5-79-B7-05-00", bson);
}
[Test]
public void WriteArrayBsonFromSite()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartArray();
writer.WriteValue("a");
writer.WriteValue("b");
writer.WriteValue("c");
writer.WriteEndArray();
writer.Flush();
ms.Seek(0, SeekOrigin.Begin);
string expected = "20-00-00-00-02-30-00-02-00-00-00-61-00-02-31-00-02-00-00-00-62-00-02-32-00-02-00-00-00-63-00-00";
string bson = BytesToHex(ms.ToArray());
Assert.AreEqual(expected, bson);
}
[Test]
public void WriteBytes()
{
byte[] data = Encoding.UTF8.GetBytes("Hello world!");
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartArray();
writer.WriteValue("a");
writer.WriteValue("b");
writer.WriteValue(data);
writer.WriteEndArray();
writer.Flush();
ms.Seek(0, SeekOrigin.Begin);
string expected = "2B-00-00-00-02-30-00-02-00-00-00-61-00-02-31-00-02-00-00-00-62-00-05-32-00-0C-00-00-00-00-48-65-6C-6C-6F-20-77-6F-72-6C-64-21-00";
string bson = BytesToHex(ms.ToArray());
Assert.AreEqual(expected, bson);
BsonReader reader = new BsonReader(new MemoryStream(ms.ToArray()));
reader.ReadRootValueAsArray = true;
reader.Read();
reader.Read();
reader.Read();
reader.Read();
Assert.AreEqual(JsonToken.Bytes, reader.TokenType);
CollectionAssert.AreEquivalent(data, (byte[])reader.Value);
}
[Test]
public void WriteNestedArray()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartObject();
writer.WritePropertyName("_id");
writer.WriteValue(HexToBytes("4A-78-93-79-17-22-00-00-00-00-61-CF"));
writer.WritePropertyName("a");
writer.WriteStartArray();
for (int i = 1; i <= 8; i++)
{
double value = (i != 5)
? Convert.ToDouble(i)
: 5.78960446186581E+77d;
writer.WriteValue(value);
}
writer.WriteEndArray();
writer.WritePropertyName("b");
writer.WriteValue("test");
writer.WriteEndObject();
writer.Flush();
ms.Seek(0, SeekOrigin.Begin);
string expected = "87-00-00-00-05-5F-69-64-00-0C-00-00-00-00-4A-78-93-79-17-22-00-00-00-00-61-CF-04-61-00-5D-00-00-00-01-30-00-00-00-00-00-00-00-F0-3F-01-31-00-00-00-00-00-00-00-00-40-01-32-00-00-00-00-00-00-00-08-40-01-33-00-00-00-00-00-00-00-10-40-01-34-00-00-00-00-00-00-00-14-50-01-35-00-00-00-00-00-00-00-18-40-01-36-00-00-00-00-00-00-00-1C-40-01-37-00-00-00-00-00-00-00-20-40-00-02-62-00-05-00-00-00-74-65-73-74-00-00";
string bson = BytesToHex(ms.ToArray());
Assert.AreEqual(expected, bson);
}
[Test]
public void WriteSerializedStore()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
Store s1 = new Store();
s1.Color = StoreColor.White;
s1.Cost = 999.59m;
s1.Employees = int.MaxValue - 1;
s1.Open = true;
s1.product.Add(new Product
{
ExpiryDate = new DateTime(2000, 9, 28, 3, 59, 58, DateTimeKind.Local),
Name = "BSON!",
Price = -0.1m,
Sizes = new[] { "First", "Second" }
});
s1.Establised = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Local);
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, s1);
ms.Seek(0, SeekOrigin.Begin);
BsonReader reader = new BsonReader(ms);
Store s2 = (Store)serializer.Deserialize(reader, typeof(Store));
Assert.AreNotEqual(s1, s2);
Assert.AreEqual(s1.Color, s2.Color);
Assert.AreEqual(s1.Cost, s2.Cost);
Assert.AreEqual(s1.Employees, s2.Employees);
Assert.AreEqual(s1.Escape, s2.Escape);
Assert.AreEqual(s1.Establised, s2.Establised);
Assert.AreEqual(s1.Mottos.Count, s2.Mottos.Count);
Assert.AreEqual(s1.Mottos.First(), s2.Mottos.First());
Assert.AreEqual(s1.Mottos.Last(), s2.Mottos.Last());
Assert.AreEqual(s1.Open, s2.Open);
Assert.AreEqual(s1.product.Count, s2.product.Count);
Assert.AreEqual(s1.RoomsPerFloor.Length, s2.RoomsPerFloor.Length);
Assert.AreEqual(s1.Symbol, s2.Symbol);
Assert.AreEqual(s1.Width, s2.Width);
MemoryStream ms1 = new MemoryStream();
BsonWriter writer1 = new BsonWriter(ms1);
serializer.Serialize(writer1, s1);
CollectionAssert.AreEquivalent(ms.ToArray(), ms1.ToArray());
string s = JsonConvert.SerializeObject(s1);
byte[] textData = Encoding.UTF8.GetBytes(s);
int l1 = textData.Length;
int l2 = ms.ToArray().Length;
Console.WriteLine(l1);
Console.WriteLine(l2);
}
[Test]
public void WriteLargeStrings()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
StringBuilder largeStringBuilder = new StringBuilder();
for (int i = 0; i < 100; i++)
{
if (i > 0)
largeStringBuilder.Append("-");
largeStringBuilder.Append(i.ToString(CultureInfo.InvariantCulture));
}
string largeString = largeStringBuilder.ToString();
writer.WriteStartObject();
writer.WritePropertyName(largeString);
writer.WriteValue(largeString);
writer.WriteEndObject();
string bson = BytesToHex(ms.ToArray());
Assert.AreEqual("4E-02-00-00-02-30-2D-31-2D-32-2D-33-2D-34-2D-35-2D-36-2D-37-2D-38-2D-39-2D-31-30-2D-31-31-2D-31-32-2D-31-33-2D-31-34-2D-31-35-2D-31-36-2D-31-37-2D-31-38-2D-31-39-2D-32-30-2D-32-31-2D-32-32-2D-32-33-2D-32-34-2D-32-35-2D-32-36-2D-32-37-2D-32-38-2D-32-39-2D-33-30-2D-33-31-2D-33-32-2D-33-33-2D-33-34-2D-33-35-2D-33-36-2D-33-37-2D-33-38-2D-33-39-2D-34-30-2D-34-31-2D-34-32-2D-34-33-2D-34-34-2D-34-35-2D-34-36-2D-34-37-2D-34-38-2D-34-39-2D-35-30-2D-35-31-2D-35-32-2D-35-33-2D-35-34-2D-35-35-2D-35-36-2D-35-37-2D-35-38-2D-35-39-2D-36-30-2D-36-31-2D-36-32-2D-36-33-2D-36-34-2D-36-35-2D-36-36-2D-36-37-2D-36-38-2D-36-39-2D-37-30-2D-37-31-2D-37-32-2D-37-33-2D-37-34-2D-37-35-2D-37-36-2D-37-37-2D-37-38-2D-37-39-2D-38-30-2D-38-31-2D-38-32-2D-38-33-2D-38-34-2D-38-35-2D-38-36-2D-38-37-2D-38-38-2D-38-39-2D-39-30-2D-39-31-2D-39-32-2D-39-33-2D-39-34-2D-39-35-2D-39-36-2D-39-37-2D-39-38-2D-39-39-00-22-01-00-00-30-2D-31-2D-32-2D-33-2D-34-2D-35-2D-36-2D-37-2D-38-2D-39-2D-31-30-2D-31-31-2D-31-32-2D-31-33-2D-31-34-2D-31-35-2D-31-36-2D-31-37-2D-31-38-2D-31-39-2D-32-30-2D-32-31-2D-32-32-2D-32-33-2D-32-34-2D-32-35-2D-32-36-2D-32-37-2D-32-38-2D-32-39-2D-33-30-2D-33-31-2D-33-32-2D-33-33-2D-33-34-2D-33-35-2D-33-36-2D-33-37-2D-33-38-2D-33-39-2D-34-30-2D-34-31-2D-34-32-2D-34-33-2D-34-34-2D-34-35-2D-34-36-2D-34-37-2D-34-38-2D-34-39-2D-35-30-2D-35-31-2D-35-32-2D-35-33-2D-35-34-2D-35-35-2D-35-36-2D-35-37-2D-35-38-2D-35-39-2D-36-30-2D-36-31-2D-36-32-2D-36-33-2D-36-34-2D-36-35-2D-36-36-2D-36-37-2D-36-38-2D-36-39-2D-37-30-2D-37-31-2D-37-32-2D-37-33-2D-37-34-2D-37-35-2D-37-36-2D-37-37-2D-37-38-2D-37-39-2D-38-30-2D-38-31-2D-38-32-2D-38-33-2D-38-34-2D-38-35-2D-38-36-2D-38-37-2D-38-38-2D-38-39-2D-39-30-2D-39-31-2D-39-32-2D-39-33-2D-39-34-2D-39-35-2D-39-36-2D-39-37-2D-39-38-2D-39-39-00-00", bson);
}
[Test]
public void SerializeGoogleGeoCode()
{
string json = @"{
""name"": ""1600 Amphitheatre Parkway, Mountain View, CA, USA"",
""Status"": {
""code"": 200,
""request"": ""geocode""
},
""Placemark"": [
{
""address"": ""1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"",
""AddressDetails"": {
""Country"": {
""CountryNameCode"": ""US"",
""AdministrativeArea"": {
""AdministrativeAreaName"": ""CA"",
""SubAdministrativeArea"": {
""SubAdministrativeAreaName"": ""Santa Clara"",
""Locality"": {
""LocalityName"": ""Mountain View"",
""Thoroughfare"": {
""ThoroughfareName"": ""1600 Amphitheatre Pkwy""
},
""PostalCode"": {
""PostalCodeNumber"": ""94043""
}
}
}
}
},
""Accuracy"": 8
},
""Point"": {
""coordinates"": [-122.083739, 37.423021, 0]
}
}
]
}";
GoogleMapGeocoderStructure jsonGoogleMapGeocoder = JsonConvert.DeserializeObject<GoogleMapGeocoderStructure>(json);
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, jsonGoogleMapGeocoder);
ms.Seek(0, SeekOrigin.Begin);
BsonReader reader = new BsonReader(ms);
GoogleMapGeocoderStructure bsonGoogleMapGeocoder = (GoogleMapGeocoderStructure)serializer.Deserialize(reader, typeof(GoogleMapGeocoderStructure));
Assert.IsNotNull(bsonGoogleMapGeocoder);
Assert.AreEqual("1600 Amphitheatre Parkway, Mountain View, CA, USA", bsonGoogleMapGeocoder.Name);
Assert.AreEqual("200", bsonGoogleMapGeocoder.Status.Code);
Assert.AreEqual("geocode", bsonGoogleMapGeocoder.Status.Request);
IList<Placemark> placemarks = bsonGoogleMapGeocoder.Placemark;
Assert.IsNotNull(placemarks);
Assert.AreEqual(1, placemarks.Count);
Placemark placemark = placemarks[0];
Assert.AreEqual("1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA", placemark.Address);
Assert.AreEqual(8, placemark.AddressDetails.Accuracy);
Assert.AreEqual("US", placemark.AddressDetails.Country.CountryNameCode);
Assert.AreEqual("CA", placemark.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName);
Assert.AreEqual("Santa Clara", placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName);
Assert.AreEqual("Mountain View", placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName);
Assert.AreEqual("1600 Amphitheatre Pkwy", placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName);
Assert.AreEqual("94043", placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber);
Assert.AreEqual(-122.083739m, placemark.Point.Coordinates[0]);
Assert.AreEqual(37.423021m, placemark.Point.Coordinates[1]);
Assert.AreEqual(0m, placemark.Point.Coordinates[2]);
}
[Test]
public void WriteEmptyStrings()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartObject();
writer.WritePropertyName("");
writer.WriteValue("");
writer.WriteEndObject();
string bson = BytesToHex(ms.ToArray());
Assert.AreEqual("0C-00-00-00-02-00-01-00-00-00-00-00", bson);
}
[Test]
public void WriteComment()
{
ExceptionAssert.Throws<JsonWriterException>("Cannot write JSON comment as BSON. Path ''.",
() =>
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartArray();
writer.WriteComment("fail");
});
}
[Test]
public void WriteConstructor()
{
ExceptionAssert.Throws<JsonWriterException>("Cannot write JSON constructor as BSON. Path ''.",
() =>
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartArray();
writer.WriteStartConstructor("fail");
});
}
[Test]
public void WriteRaw()
{
ExceptionAssert.Throws<JsonWriterException>("Cannot write raw JSON as BSON. Path ''.",
() =>
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartArray();
writer.WriteRaw("fail");
});
}
[Test]
public void WriteRawValue()
{
ExceptionAssert.Throws<JsonWriterException>("Cannot write raw JSON as BSON. Path ''.",
() =>
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartArray();
writer.WriteRawValue("fail");
});
}
[Test]
public void Example()
{
Product p = new Product();
p.ExpiryDate = DateTime.Parse("2009-04-05T14:45:00Z");
p.Name = "Carlos' Spicy Wieners";
p.Price = 9.95m;
p.Sizes = new[] { "Small", "Medium", "Large" };
MemoryStream ms = new MemoryStream();
JsonSerializer serializer = new JsonSerializer();
// serialize product to BSON
BsonWriter writer = new BsonWriter(ms);
serializer.Serialize(writer, p);
Console.WriteLine(BitConverter.ToString(ms.ToArray()));
// 7C-00-00-00-02-4E-61-6D-65-00-16-00-00-00-43-61-72-6C-
// 6F-73-27-20-53-70-69-63-79-20-57-69-65-6E-65-72-73-00-
// 09-45-78-70-69-72-79-44-61-74-65-00-E0-51-BD-76-20-01-
// 00-00-01-50-72-69-63-65-00-66-66-66-66-66-E6-23-40-04-
// 53-69-7A-65-73-00-2D-00-00-00-02-30-00-06-00-00-00-53-
// 6D-61-6C-6C-00-02-31-00-07-00-00-00-4D-65-64-69-75-6D-
// 00-02-32-00-06-00-00-00-4C-61-72-67-65-00-00-00
ms.Seek(0, SeekOrigin.Begin);
// deserialize product from BSON
BsonReader reader = new BsonReader(ms);
Product deserializedProduct = serializer.Deserialize<Product>(reader);
Console.WriteLine(deserializedProduct.Name);
// Carlos' Spicy Wieners
Assert.AreEqual("Carlos' Spicy Wieners", deserializedProduct.Name);
Assert.AreEqual(9.95m, deserializedProduct.Price);
Assert.AreEqual(3, deserializedProduct.Sizes.Length);
}
[Test]
public void WriteOid()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
byte[] oid = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
writer.WriteStartObject();
writer.WritePropertyName("_oid");
writer.WriteObjectId(oid);
writer.WriteEndObject();
string bson = BytesToHex(ms.ToArray());
Assert.AreEqual("17-00-00-00-07-5F-6F-69-64-00-01-02-03-04-05-06-07-08-09-0A-0B-0C-00", bson);
ms.Seek(0, SeekOrigin.Begin);
BsonReader reader = new BsonReader(ms);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.Bytes, reader.TokenType);
CollectionAssert.AreEquivalent(oid, (byte[])reader.Value);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
}
[Test]
public void WriteOidPlusContent()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartObject();
writer.WritePropertyName("_id");
writer.WriteObjectId(HexToBytes("4ABBED9D1D8B0F0218000001"));
writer.WritePropertyName("test");
writer.WriteValue("1234£56");
writer.WriteEndObject();
byte[] expected = HexToBytes("29000000075F6964004ABBED9D1D8B0F02180000010274657374000900000031323334C2A335360000");
CollectionAssert.AreEquivalent(expected, ms.ToArray());
}
[Test]
public void WriteRegexPlusContent()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartObject();
writer.WritePropertyName("regex");
writer.WriteRegex("abc", "i");
writer.WritePropertyName("test");
writer.WriteRegex(string.Empty, null);
writer.WriteEndObject();
byte[] expected = HexToBytes("1A-00-00-00-0B-72-65-67-65-78-00-61-62-63-00-69-00-0B-74-65-73-74-00-00-00-00");
CollectionAssert.AreEquivalent(expected, ms.ToArray());
}
[Test]
public void SerializeEmptyAndNullStrings()
{
Product p = new Product();
p.ExpiryDate = DateTime.Parse("2009-04-05T14:45:00Z");
p.Name = null;
p.Price = 9.95m;
p.Sizes = new[] { "Small", "", null };
MemoryStream ms = new MemoryStream();
JsonSerializer serializer = new JsonSerializer();
BsonWriter writer = new BsonWriter(ms);
serializer.Serialize(writer, p);
ms.Seek(0, SeekOrigin.Begin);
BsonReader reader = new BsonReader(ms);
Product deserializedProduct = serializer.Deserialize<Product>(reader);
Console.WriteLine(deserializedProduct.Name);
Assert.AreEqual(null, deserializedProduct.Name);
Assert.AreEqual(9.95m, deserializedProduct.Price);
Assert.AreEqual(3, deserializedProduct.Sizes.Length);
Assert.AreEqual("Small", deserializedProduct.Sizes[0]);
Assert.AreEqual("", deserializedProduct.Sizes[1]);
Assert.AreEqual(null, deserializedProduct.Sizes[2]);
}
[Test]
public void WriteReadEmptyAndNullStrings()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartArray();
writer.WriteValue("Content!");
writer.WriteValue("");
writer.WriteValue((string)null);
writer.WriteEndArray();
ms.Seek(0, SeekOrigin.Begin);
BsonReader reader = new BsonReader(ms);
reader.ReadRootValueAsArray = true;
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartArray, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.AreEqual("Content!", reader.Value);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.AreEqual("", reader.Value);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.Null, reader.TokenType);
Assert.AreEqual(null, reader.Value);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndArray, reader.TokenType);
Assert.IsFalse(reader.Read());
}
[Test]
public void WriteDateTimes()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.DateTimeKindHandling = DateTimeKind.Unspecified;
writer.WriteStartArray();
writer.WriteValue(new DateTime(2000, 10, 12, 20, 55, 0, DateTimeKind.Utc));
writer.WriteValue(new DateTime(2000, 10, 12, 20, 55, 0, DateTimeKind.Local));
writer.WriteValue(new DateTime(2000, 10, 12, 20, 55, 0, DateTimeKind.Unspecified));
writer.WriteEndArray();
ms.Seek(0, SeekOrigin.Begin);
BsonReader reader = new BsonReader(ms);
reader.ReadRootValueAsArray = true;
reader.DateTimeKindHandling = DateTimeKind.Utc;
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartArray, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.Date, reader.TokenType);
Assert.AreEqual(new DateTime(2000, 10, 12, 20, 55, 0, DateTimeKind.Utc), reader.Value);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.Date, reader.TokenType);
Assert.AreEqual(new DateTime(2000, 10, 12, 20, 55, 0, DateTimeKind.Utc), reader.Value);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.Date, reader.TokenType);
Assert.AreEqual(new DateTime(2000, 10, 12, 20, 55, 0, DateTimeKind.Utc), reader.Value);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndArray, reader.TokenType);
Assert.IsFalse(reader.Read());
}
[Test]
public void WriteValueOutsideOfObjectOrArray()
{
ExceptionAssert.Throws<JsonWriterException>("Error writing String value. BSON must start with an Object or Array. Path ''.",
() =>
{
MemoryStream stream = new MemoryStream();
using (BsonWriter writer = new BsonWriter(stream))
{
writer.WriteValue("test");
writer.Flush();
}
});
}
[Test]
public void DateTimeZoneHandling()
{
MemoryStream ms = new MemoryStream();
JsonWriter writer = new BsonWriter(ms)
{
DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc
};
writer.WriteStartArray();
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified));
writer.WriteEndArray();
Assert.AreEqual("10-00-00-00-09-30-00-C8-88-07-6B-DC-00-00-00-00", (BitConverter.ToString(ms.ToArray())));
}
public class RegexTestClass
{
public Regex Regex { get; set; }
}
[Test]
public void SerializeDeserializeRegex()
{
Regex r1 = new Regex("(hi)", RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
RegexTestClass c = new RegexTestClass { Regex = r1 };
MemoryStream ms = new MemoryStream();
JsonSerializer serializer = new JsonSerializer();
BsonWriter writer = new BsonWriter(ms);
serializer.Serialize(writer, c);
string hex = BitConverter.ToString(ms.ToArray());
Assert.AreEqual("15-00-00-00-0B-52-65-67-65-78-00-28-68-69-29-00-69-75-78-00-00", hex);
JObject o = (JObject)JObject.ReadFrom(new BsonReader(new MemoryStream(ms.ToArray())));
Console.WriteLine(o.ToString());
//{
// "Regex": "/(hi)/iux"
//}
}
[Test]
public void SerializeByteArray_ErrorWhenTopLevel()
{
byte[] b = Encoding.UTF8.GetBytes("Hello world");
MemoryStream ms = new MemoryStream();
JsonSerializer serializer = new JsonSerializer();
BsonWriter writer = new BsonWriter(ms);
ExceptionAssert.Throws<JsonWriterException>("Error writing Binary value. BSON must start with an Object or Array. Path ''.",
() =>
{
serializer.Serialize(writer, b);
});
}
public class GuidTestClass
{
public Guid AGuid { get; set; }
}
public class StringTestClass
{
public string AGuid { get; set; }
}
[Test]
public void WriteReadGuid()
{
GuidTestClass c = new GuidTestClass();
c.AGuid = new Guid("af45dccf-df13-44fe-82be-6212c09eda84");
MemoryStream ms = new MemoryStream();
JsonSerializer serializer = new JsonSerializer();
BsonWriter writer = new BsonWriter(ms);
serializer.Serialize(writer, c);
ms.Seek(0, SeekOrigin.Begin);
BsonReader reader = new BsonReader(ms);
GuidTestClass c2 = serializer.Deserialize<GuidTestClass>(reader);
Assert.AreEqual(c.AGuid, c2.AGuid);
}
[Test]
public void WriteStringReadGuid()
{
StringTestClass c = new StringTestClass();
c.AGuid = new Guid("af45dccf-df13-44fe-82be-6212c09eda84").ToString();
MemoryStream ms = new MemoryStream();
JsonSerializer serializer = new JsonSerializer();
BsonWriter writer = new BsonWriter(ms);
serializer.Serialize(writer, c);
ms.Seek(0, SeekOrigin.Begin);
BsonReader reader = new BsonReader(ms);
GuidTestClass c2 = serializer.Deserialize<GuidTestClass>(reader);
Assert.AreEqual(c.AGuid, c2.AGuid.ToString());
}
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
[Test]
public void WriteBigInteger()
{
BigInteger i = BigInteger.Parse("1999999999999999999999999999999999999999999999999999999999990");
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartObject();
writer.WritePropertyName("Blah");
writer.WriteValue(i);
writer.WriteEndObject();
string bson = BytesToHex(ms.ToArray());
Assert.AreEqual("2A-00-00-00-05-42-6C-61-68-00-1A-00-00-00-00-F6-FF-FF-FF-FF-FF-FF-1F-B2-21-CB-28-59-84-C4-AE-03-8A-44-34-2F-4C-4E-9E-3E-01-00", bson);
ms.Seek(0, SeekOrigin.Begin);
BsonReader reader = new BsonReader(ms);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.Bytes, reader.TokenType);
CollectionAssert.AreEqual(new byte[] { 246, 255, 255, 255, 255, 255, 255, 31, 178, 33, 203, 40, 89, 132, 196, 174, 3, 138, 68, 52, 47, 76, 78, 158, 62, 1 }, (byte[])reader.Value);
Assert.AreEqual(i, new BigInteger((byte[])reader.Value));
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
Assert.IsFalse(reader.Read());
}
#endif
}
}

View File

@@ -0,0 +1,194 @@
#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
using System;
using System.Collections.Generic;
#if !NET20 && !NETFX_CORE
using System.Data.Linq;
#endif
#if !(NETFX_CORE)
using System.Data.SqlTypes;
#endif
using System.Text;
using Newtonsoft.Json.Converters;
#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
namespace Newtonsoft.Json.Tests.Converters
{
[TestFixture]
public class BinaryConverterTests : TestFixtureBase
{
private static readonly byte[] TestData = Encoding.UTF8.GetBytes("This is some test data!!!");
public class ByteArrayClass
{
public byte[] ByteArray { get; set; }
public byte[] NullByteArray { get; set; }
}
#if !(NET20 || NETFX_CORE || PORTABLE || PORTABLE40)
[Test]
public void DeserializeBinaryClass()
{
string json = @"{
""Binary"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
""NullBinary"": null
}";
BinaryClass binaryClass = JsonConvert.DeserializeObject<BinaryClass>(json, new BinaryConverter());
Assert.AreEqual(new Binary(TestData), binaryClass.Binary);
Assert.AreEqual(null, binaryClass.NullBinary);
}
[Test]
public void DeserializeBinaryClassFromJsonArray()
{
string json = @"{
""Binary"": [0, 1, 2, 3],
""NullBinary"": null
}";
BinaryClass binaryClass = JsonConvert.DeserializeObject<BinaryClass>(json, new BinaryConverter());
Assert.AreEqual(new byte[] { 0, 1, 2, 3 }, binaryClass.Binary.ToArray());
Assert.AreEqual(null, binaryClass.NullBinary);
}
public class BinaryClass
{
public Binary Binary { get; set; }
public Binary NullBinary { get; set; }
}
[Test]
public void SerializeBinaryClass()
{
BinaryClass binaryClass = new BinaryClass();
binaryClass.Binary = new Binary(TestData);
binaryClass.NullBinary = null;
string json = JsonConvert.SerializeObject(binaryClass, Formatting.Indented, new BinaryConverter());
Assert.AreEqual(@"{
""Binary"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
""NullBinary"": null
}", json);
}
#endif
[Test]
public void SerializeByteArrayClass()
{
ByteArrayClass byteArrayClass = new ByteArrayClass();
byteArrayClass.ByteArray = TestData;
byteArrayClass.NullByteArray = null;
string json = JsonConvert.SerializeObject(byteArrayClass, Formatting.Indented);
Assert.AreEqual(@"{
""ByteArray"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
""NullByteArray"": null
}", json);
}
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
public class SqlBinaryClass
{
public SqlBinary SqlBinary { get; set; }
public SqlBinary? NullableSqlBinary1 { get; set; }
public SqlBinary? NullableSqlBinary2 { get; set; }
}
[Test]
public void SerializeSqlBinaryClass()
{
SqlBinaryClass sqlBinaryClass = new SqlBinaryClass();
sqlBinaryClass.SqlBinary = new SqlBinary(TestData);
sqlBinaryClass.NullableSqlBinary1 = new SqlBinary(TestData);
sqlBinaryClass.NullableSqlBinary2 = null;
string json = JsonConvert.SerializeObject(sqlBinaryClass, Formatting.Indented, new BinaryConverter());
Assert.AreEqual(@"{
""SqlBinary"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
""NullableSqlBinary1"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
""NullableSqlBinary2"": null
}", json);
}
[Test]
public void DeserializeSqlBinaryClass()
{
string json = @"{
""SqlBinary"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
""NullableSqlBinary1"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
""NullableSqlBinary2"": null
}";
SqlBinaryClass sqlBinaryClass = JsonConvert.DeserializeObject<SqlBinaryClass>(json, new BinaryConverter());
Assert.AreEqual(new SqlBinary(TestData), sqlBinaryClass.SqlBinary);
Assert.AreEqual(new SqlBinary(TestData), sqlBinaryClass.NullableSqlBinary1);
Assert.AreEqual(null, sqlBinaryClass.NullableSqlBinary2);
}
#endif
[Test]
public void DeserializeByteArrayClass()
{
string json = @"{
""ByteArray"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
""NullByteArray"": null
}";
ByteArrayClass byteArrayClass = JsonConvert.DeserializeObject<ByteArrayClass>(json);
CollectionAssert.AreEquivalent(TestData, byteArrayClass.ByteArray);
Assert.AreEqual(null, byteArrayClass.NullByteArray);
}
[Test]
public void DeserializeByteArrayFromJsonArray()
{
string json = @"{
""ByteArray"": [0, 1, 2, 3],
""NullByteArray"": null
}";
ByteArrayClass c = JsonConvert.DeserializeObject<ByteArrayClass>(json);
Assert.IsNotNull(c.ByteArray);
Assert.AreEqual(4, c.ByteArray.Length);
CollectionAssert.AreEquivalent(new byte[] { 0, 1, 2, 3 }, c.ByteArray);
}
}
}

View File

@@ -0,0 +1,261 @@
#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
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
#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
namespace Newtonsoft.Json.Tests.Converters
{
[TestFixture]
public class CustomCreationConverterTests : TestFixtureBase
{
public interface IPerson
{
string FirstName { get; set; }
string LastName { get; set; }
DateTime BirthDate { get; set; }
}
public class Employee : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public string Department { get; set; }
public string JobTitle { get; set; }
}
public class PersonConverter : CustomCreationConverter<IPerson>
{
public override IPerson Create(Type objectType)
{
return new Employee();
}
}
public void DeserializeObject()
{
string json = JsonConvert.SerializeObject(new List<Employee>
{
new Employee
{
BirthDate = new DateTime(1977, 12, 30, 1, 1, 1, DateTimeKind.Utc),
FirstName = "Maurice",
LastName = "Moss",
Department = "IT",
JobTitle = "Support"
},
new Employee
{
BirthDate = new DateTime(1978, 3, 15, 1, 1, 1, DateTimeKind.Utc),
FirstName = "Jen",
LastName = "Barber",
Department = "IT",
JobTitle = "Manager"
}
}, Formatting.Indented);
//[
// {
// "FirstName": "Maurice",
// "LastName": "Moss",
// "BirthDate": "\/Date(252291661000)\/",
// "Department": "IT",
// "JobTitle": "Support"
// },
// {
// "FirstName": "Jen",
// "LastName": "Barber",
// "BirthDate": "\/Date(258771661000)\/",
// "Department": "IT",
// "JobTitle": "Manager"
// }
//]
List<IPerson> people = JsonConvert.DeserializeObject<List<IPerson>>(json, new PersonConverter());
IPerson person = people[0];
Console.WriteLine(person.GetType());
// Newtonsoft.Json.Tests.Employee
Console.WriteLine(person.FirstName);
// Maurice
Employee employee = (Employee)person;
Console.WriteLine(employee.JobTitle);
// Support
}
public class MyClass
{
public string Value { get; set; }
[JsonConverter(typeof(MyThingConverter))]
public IThing Thing { get; set; }
}
public interface IThing
{
int Number { get; }
}
public class MyThing : IThing
{
public int Number { get; set; }
}
public class MyThingConverter : CustomCreationConverter<IThing>
{
public override IThing Create(Type objectType)
{
return new MyThing();
}
}
[Test]
public void AssertDoesDeserialize()
{
const string json = @"{
""Value"": ""A value"",
""Thing"": {
""Number"": 123
}
}
";
MyClass myClass = JsonConvert.DeserializeObject<MyClass>(json);
Assert.IsNotNull(myClass);
Assert.AreEqual("A value", myClass.Value);
Assert.IsNotNull(myClass.Thing);
Assert.AreEqual(123, myClass.Thing.Number);
}
[Test]
public void AssertShouldSerializeTest()
{
MyClass myClass = new MyClass
{
Value = "Foo",
Thing = new MyThing { Number = 456, }
};
string json = JsonConvert.SerializeObject(myClass); // <-- Exception here
const string expected = @"{""Value"":""Foo"",""Thing"":{""Number"":456}}";
Assert.AreEqual(expected, json);
}
internal interface IRange<T>
{
T First { get; }
T Last { get; }
}
internal class Range<T> : IRange<T>
{
public T First { get; set; }
public T Last { get; set; }
}
internal class NullInterfaceTestClass
{
public virtual Guid Id { get; set; }
public virtual int? Year { get; set; }
public virtual string Company { get; set; }
public virtual IRange<decimal> DecimalRange { get; set; }
public virtual IRange<int> IntRange { get; set; }
public virtual IRange<decimal> NullDecimalRange { get; set; }
}
internal class DecimalRangeConverter : CustomCreationConverter<IRange<decimal>>
{
public override IRange<decimal> Create(Type objectType)
{
return new Range<decimal>();
}
}
internal class IntRangeConverter : CustomCreationConverter<IRange<int>>
{
public override IRange<int> Create(Type objectType)
{
return new Range<int>();
}
}
[Test]
public void DeserializeAndConvertNullValue()
{
NullInterfaceTestClass initial = new NullInterfaceTestClass
{
Company = "Company!",
DecimalRange = new Range<decimal> { First = 0, Last = 1 },
Id = new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11),
IntRange = new Range<int> { First = int.MinValue, Last = int.MaxValue },
Year = 2010,
NullDecimalRange = null
};
string json = JsonConvert.SerializeObject(initial, Formatting.Indented);
Assert.AreEqual(@"{
""Id"": ""00000001-0002-0003-0405-060708090a0b"",
""Year"": 2010,
""Company"": ""Company!"",
""DecimalRange"": {
""First"": 0.0,
""Last"": 1.0
},
""IntRange"": {
""First"": -2147483648,
""Last"": 2147483647
},
""NullDecimalRange"": null
}", json);
NullInterfaceTestClass deserialized = JsonConvert.DeserializeObject<NullInterfaceTestClass>(
json, new IntRangeConverter(), new DecimalRangeConverter());
Assert.AreEqual("Company!", deserialized.Company);
Assert.AreEqual(new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), deserialized.Id);
Assert.AreEqual(0, deserialized.DecimalRange.First);
Assert.AreEqual(1, deserialized.DecimalRange.Last);
Assert.AreEqual(int.MinValue, deserialized.IntRange.First);
Assert.AreEqual(int.MaxValue, deserialized.IntRange.Last);
Assert.AreEqual(null, deserialized.NullDecimalRange);
Assert.AreEqual(2010, deserialized.Year);
}
}
}

View File

@@ -0,0 +1,458 @@
#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 !(NETFX_CORE || PORTABLE || PORTABLE40)
using System;
using Newtonsoft.Json.Converters;
#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.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using System.Data;
namespace Newtonsoft.Json.Tests.Converters
{
public class DataSetConverterTests : TestFixtureBase
{
[Test]
public void SerializeAndDeserialize()
{
DataSet dataSet = new DataSet("dataSet");
dataSet.Namespace = "NetFrameWork";
DataTable table = new DataTable();
DataColumn idColumn = new DataColumn("id", typeof(int));
idColumn.AutoIncrement = true;
DataColumn itemColumn = new DataColumn("item");
table.Columns.Add(idColumn);
table.Columns.Add(itemColumn);
dataSet.Tables.Add(table);
for (int i = 0; i < 2; i++)
{
DataRow newRow = table.NewRow();
newRow["item"] = "item " + i;
table.Rows.Add(newRow);
}
dataSet.AcceptChanges();
string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
Assert.AreEqual(@"{
""Table1"": [
{
""id"": 0,
""item"": ""item 0""
},
{
""id"": 1,
""item"": ""item 1""
}
]
}", json);
DataSet deserializedDataSet = JsonConvert.DeserializeObject<DataSet>(json);
Assert.IsNotNull(deserializedDataSet);
Assert.AreEqual(1, deserializedDataSet.Tables.Count);
DataTable dt = deserializedDataSet.Tables[0];
Assert.AreEqual("Table1", dt.TableName);
Assert.AreEqual(2, dt.Columns.Count);
Assert.AreEqual("id", dt.Columns[0].ColumnName);
Assert.AreEqual(typeof(long), dt.Columns[0].DataType);
Assert.AreEqual("item", dt.Columns[1].ColumnName);
Assert.AreEqual(typeof(string), dt.Columns[1].DataType);
Assert.AreEqual(2, dt.Rows.Count);
}
[Test]
public void SerializeMultiTableDataSet()
{
DataSet ds = new DataSet();
ds.Tables.Add(CreateDataTable("FirstTable", 2));
ds.Tables.Add(CreateDataTable("SecondTable", 1));
string json = JsonConvert.SerializeObject(ds, Formatting.Indented, new IsoDateTimeConverter());
// {
// "FirstTable": [
// {
// "StringCol": "Item Name",
// "Int32Col": 1,
// "BooleanCol": true,
// "TimeSpanCol": "10.22:10:15.1000000",
// "DateTimeCol": "2000-12-29T00:00:00Z",
// "DecimalCol": 64.0021
// },
// {
// "StringCol": "Item Name",
// "Int32Col": 2,
// "BooleanCol": true,
// "TimeSpanCol": "10.22:10:15.1000000",
// "DateTimeCol": "2000-12-29T00:00:00Z",
// "DecimalCol": 64.0021
// }
// ],
// "SecondTable": [
// {
// "StringCol": "Item Name",
// "Int32Col": 1,
// "BooleanCol": true,
// "TimeSpanCol": "10.22:10:15.1000000",
// "DateTimeCol": "2000-12-29T00:00:00Z",
// "DecimalCol": 64.0021
// }
// ]
// }
DataSet deserializedDs = JsonConvert.DeserializeObject<DataSet>(json, new IsoDateTimeConverter());
Assert.AreEqual(@"{
""FirstTable"": [
{
""StringCol"": ""Item Name"",
""Int32Col"": 1,
""BooleanCol"": true,
""TimeSpanCol"": ""10.22:10:15.1000000"",
""DateTimeCol"": ""2000-12-29T00:00:00Z"",
""DecimalCol"": 64.0021
},
{
""StringCol"": ""Item Name"",
""Int32Col"": 2,
""BooleanCol"": true,
""TimeSpanCol"": ""10.22:10:15.1000000"",
""DateTimeCol"": ""2000-12-29T00:00:00Z"",
""DecimalCol"": 64.0021
}
],
""SecondTable"": [
{
""StringCol"": ""Item Name"",
""Int32Col"": 1,
""BooleanCol"": true,
""TimeSpanCol"": ""10.22:10:15.1000000"",
""DateTimeCol"": ""2000-12-29T00:00:00Z"",
""DecimalCol"": 64.0021
}
]
}", json);
Assert.IsNotNull(deserializedDs);
}
[Test]
public void DeserializeMultiTableDataSet()
{
string json = @"{
""FirstTable"": [
{
""StringCol"": ""Item Name"",
""Int32Col"": 2147483647,
""BooleanCol"": true,
""TimeSpanCol"": ""10.22:10:15.1000000"",
""DateTimeCol"": ""2000-12-29T00:00:00Z"",
""DecimalCol"": 64.0021
}
],
""SecondTable"": [
{
""StringCol"": ""Item Name"",
""Int32Col"": 2147483647,
""BooleanCol"": true,
""TimeSpanCol"": ""10.22:10:15.1000000"",
""DateTimeCol"": ""2000-12-29T00:00:00Z"",
""DecimalCol"": 64.0021
}
]
}";
DataSet ds = JsonConvert.DeserializeObject<DataSet>(json);
Assert.IsNotNull(ds);
Assert.AreEqual(2, ds.Tables.Count);
Assert.AreEqual("FirstTable", ds.Tables[0].TableName);
Assert.AreEqual("SecondTable", ds.Tables[1].TableName);
DataTable dt = ds.Tables[0];
Assert.AreEqual("StringCol", dt.Columns[0].ColumnName);
Assert.AreEqual(typeof(string), dt.Columns[0].DataType);
Assert.AreEqual("Int32Col", dt.Columns[1].ColumnName);
Assert.AreEqual(typeof(long), dt.Columns[1].DataType);
Assert.AreEqual("BooleanCol", dt.Columns[2].ColumnName);
Assert.AreEqual(typeof(bool), dt.Columns[2].DataType);
Assert.AreEqual("TimeSpanCol", dt.Columns[3].ColumnName);
Assert.AreEqual(typeof(string), dt.Columns[3].DataType);
Assert.AreEqual("DateTimeCol", dt.Columns[4].ColumnName);
Assert.AreEqual(typeof(DateTime), dt.Columns[4].DataType);
Assert.AreEqual("DecimalCol", dt.Columns[5].ColumnName);
Assert.AreEqual(typeof(double), dt.Columns[5].DataType);
Assert.AreEqual(1, ds.Tables[0].Rows.Count);
Assert.AreEqual(1, ds.Tables[1].Rows.Count);
}
private DataTable CreateDataTable(string dataTableName, int rows)
{
// create a new DataTable.
DataTable myTable = new DataTable(dataTableName);
// create DataColumn objects of data types.
DataColumn colString = new DataColumn("StringCol");
colString.DataType = typeof(string);
myTable.Columns.Add(colString);
DataColumn colInt32 = new DataColumn("Int32Col");
colInt32.DataType = typeof(int);
myTable.Columns.Add(colInt32);
DataColumn colBoolean = new DataColumn("BooleanCol");
colBoolean.DataType = typeof(bool);
myTable.Columns.Add(colBoolean);
DataColumn colTimeSpan = new DataColumn("TimeSpanCol");
colTimeSpan.DataType = typeof(TimeSpan);
myTable.Columns.Add(colTimeSpan);
DataColumn colDateTime = new DataColumn("DateTimeCol");
colDateTime.DataType = typeof(DateTime);
colDateTime.DateTimeMode = DataSetDateTime.Utc;
myTable.Columns.Add(colDateTime);
DataColumn colDecimal = new DataColumn("DecimalCol");
colDecimal.DataType = typeof(decimal);
myTable.Columns.Add(colDecimal);
for (int i = 1; i <= rows; i++)
{
DataRow myNewRow = myTable.NewRow();
myNewRow["StringCol"] = "Item Name";
myNewRow["Int32Col"] = i;
myNewRow["BooleanCol"] = true;
myNewRow["TimeSpanCol"] = new TimeSpan(10, 22, 10, 15, 100);
myNewRow["DateTimeCol"] = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc);
myNewRow["DecimalCol"] = 64.0021;
myTable.Rows.Add(myNewRow);
}
return myTable;
}
public class DataSetAndTableTestClass
{
public string Before { get; set; }
public DataSet Set { get; set; }
public string Middle { get; set; }
public DataTable Table { get; set; }
public string After { get; set; }
}
[Test]
public void SerializeWithCamelCaseResolver()
{
DataSet ds = new DataSet();
ds.Tables.Add(CreateDataTable("FirstTable", 2));
ds.Tables.Add(CreateDataTable("SecondTable", 1));
string json = JsonConvert.SerializeObject(ds, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(@"{
""firstTable"": [
{
""stringCol"": ""Item Name"",
""int32Col"": 1,
""booleanCol"": true,
""timeSpanCol"": ""10.22:10:15.1000000"",
""dateTimeCol"": ""2000-12-29T00:00:00Z"",
""decimalCol"": 64.0021
},
{
""stringCol"": ""Item Name"",
""int32Col"": 2,
""booleanCol"": true,
""timeSpanCol"": ""10.22:10:15.1000000"",
""dateTimeCol"": ""2000-12-29T00:00:00Z"",
""decimalCol"": 64.0021
}
],
""secondTable"": [
{
""stringCol"": ""Item Name"",
""int32Col"": 1,
""booleanCol"": true,
""timeSpanCol"": ""10.22:10:15.1000000"",
""dateTimeCol"": ""2000-12-29T00:00:00Z"",
""decimalCol"": 64.0021
}
]
}", json);
}
[Test]
public void SerializeDataSetProperty()
{
DataSet ds = new DataSet();
ds.Tables.Add(CreateDataTable("FirstTable", 2));
ds.Tables.Add(CreateDataTable("SecondTable", 1));
DataSetAndTableTestClass c = new DataSetAndTableTestClass
{
Before = "Before",
Set = ds,
Middle = "Middle",
Table = CreateDataTable("LoneTable", 2),
After = "After"
};
string json = JsonConvert.SerializeObject(c, Formatting.Indented, new IsoDateTimeConverter());
Assert.AreEqual(@"{
""Before"": ""Before"",
""Set"": {
""FirstTable"": [
{
""StringCol"": ""Item Name"",
""Int32Col"": 1,
""BooleanCol"": true,
""TimeSpanCol"": ""10.22:10:15.1000000"",
""DateTimeCol"": ""2000-12-29T00:00:00Z"",
""DecimalCol"": 64.0021
},
{
""StringCol"": ""Item Name"",
""Int32Col"": 2,
""BooleanCol"": true,
""TimeSpanCol"": ""10.22:10:15.1000000"",
""DateTimeCol"": ""2000-12-29T00:00:00Z"",
""DecimalCol"": 64.0021
}
],
""SecondTable"": [
{
""StringCol"": ""Item Name"",
""Int32Col"": 1,
""BooleanCol"": true,
""TimeSpanCol"": ""10.22:10:15.1000000"",
""DateTimeCol"": ""2000-12-29T00:00:00Z"",
""DecimalCol"": 64.0021
}
]
},
""Middle"": ""Middle"",
""Table"": [
{
""StringCol"": ""Item Name"",
""Int32Col"": 1,
""BooleanCol"": true,
""TimeSpanCol"": ""10.22:10:15.1000000"",
""DateTimeCol"": ""2000-12-29T00:00:00Z"",
""DecimalCol"": 64.0021
},
{
""StringCol"": ""Item Name"",
""Int32Col"": 2,
""BooleanCol"": true,
""TimeSpanCol"": ""10.22:10:15.1000000"",
""DateTimeCol"": ""2000-12-29T00:00:00Z"",
""DecimalCol"": 64.0021
}
],
""After"": ""After""
}", json);
DataSetAndTableTestClass c2 = JsonConvert.DeserializeObject<DataSetAndTableTestClass>(json, new IsoDateTimeConverter());
Assert.AreEqual(c.Before, c2.Before);
Assert.AreEqual(c.Set.Tables.Count, c2.Set.Tables.Count);
Assert.AreEqual(c.Middle, c2.Middle);
Assert.AreEqual(c.Table.Rows.Count, c2.Table.Rows.Count);
Assert.AreEqual(c.After, c2.After);
}
[Test]
public void SerializedTypedDataSet()
{
CustomerDataSet ds = new CustomerDataSet();
ds.Customers.AddCustomersRow("234");
string json = JsonConvert.SerializeObject(ds, Formatting.Indented);
Assert.AreEqual(@"{
""Customers"": [
{
""CustomerID"": ""234""
}
]
}", json);
CustomerDataSet ds1 = new CustomerDataSet();
DataTable table = ds1.Tables["Customers"];
DataRow row = ds1.Tables["Customers"].NewRow();
row["CustomerID"] = "234";
table.Rows.Add(row);
string json1 = JsonConvert.SerializeObject(ds1, Formatting.Indented);
Assert.AreEqual(@"{
""Customers"": [
{
""CustomerID"": ""234""
}
]
}", json1);
}
[Test]
public void DeserializedTypedDataSet()
{
string json = @"{
""Customers"": [
{
""CustomerID"": ""234""
}
]
}";
var ds = JsonConvert.DeserializeObject<CustomerDataSet>(json);
Assert.AreEqual("234", ds.Customers[0].CustomerID);
}
}
}
#endif

View File

@@ -0,0 +1,365 @@
#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
using System.Text;
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
using System;
using System.Collections.Generic;
#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
#if !NETFX_CORE
using System.Data;
#endif
using Newtonsoft.Json.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Converters
{
public class DataTableConverterTests : TestFixtureBase
{
[Test]
public void Deserialize()
{
string json = @"[
{
""id"": 0,
""item"": ""item 0"",
""DataTableCol"": [
{
""NestedStringCol"": ""0!""
}
],
""ArrayCol"": [
0
]
},
{
""id"": 1,
""item"": ""item 1"",
""DataTableCol"": [
{
""NestedStringCol"": ""1!""
}
],
""ArrayCol"": [
1
]
}
]";
DataTable deserializedDataTable = JsonConvert.DeserializeObject<DataTable>(json);
Assert.IsNotNull(deserializedDataTable);
Assert.AreEqual(string.Empty, deserializedDataTable.TableName);
Assert.AreEqual(4, deserializedDataTable.Columns.Count);
Assert.AreEqual("id", deserializedDataTable.Columns[0].ColumnName);
Assert.AreEqual(typeof(long), deserializedDataTable.Columns[0].DataType);
Assert.AreEqual("item", deserializedDataTable.Columns[1].ColumnName);
Assert.AreEqual(typeof(string), deserializedDataTable.Columns[1].DataType);
Assert.AreEqual("DataTableCol", deserializedDataTable.Columns[2].ColumnName);
Assert.AreEqual(typeof(DataTable), deserializedDataTable.Columns[2].DataType);
Assert.AreEqual("ArrayCol", deserializedDataTable.Columns[3].ColumnName);
Assert.AreEqual(typeof(long[]), deserializedDataTable.Columns[3].DataType);
Assert.AreEqual(2, deserializedDataTable.Rows.Count);
DataRow dr1 = deserializedDataTable.Rows[0];
Assert.AreEqual(0, dr1["id"]);
Assert.AreEqual("item 0", dr1["item"]);
Assert.AreEqual("0!", ((DataTable)dr1["DataTableCol"]).Rows[0]["NestedStringCol"]);
Assert.AreEqual(0, ((long[])dr1["ArrayCol"])[0]);
DataRow dr2 = deserializedDataTable.Rows[1];
Assert.AreEqual(1, dr2["id"]);
Assert.AreEqual("item 1", dr2["item"]);
Assert.AreEqual("1!", ((DataTable)dr2["DataTableCol"]).Rows[0]["NestedStringCol"]);
Assert.AreEqual(1, ((long[])dr2["ArrayCol"])[0]);
}
[Test]
public void Serialize()
{
// create a new DataTable.
DataTable myTable = new DataTable("blah");
// create DataColumn objects of data types.
DataColumn colString = new DataColumn("StringCol");
colString.DataType = typeof(string);
myTable.Columns.Add(colString);
DataColumn colInt32 = new DataColumn("Int32Col");
colInt32.DataType = typeof(int);
myTable.Columns.Add(colInt32);
DataColumn colBoolean = new DataColumn("BooleanCol");
colBoolean.DataType = typeof(bool);
myTable.Columns.Add(colBoolean);
DataColumn colTimeSpan = new DataColumn("TimeSpanCol");
colTimeSpan.DataType = typeof(TimeSpan);
myTable.Columns.Add(colTimeSpan);
DataColumn colDateTime = new DataColumn("DateTimeCol");
colDateTime.DataType = typeof(DateTime);
colDateTime.DateTimeMode = DataSetDateTime.Utc;
myTable.Columns.Add(colDateTime);
DataColumn colDecimal = new DataColumn("DecimalCol");
colDecimal.DataType = typeof(decimal);
myTable.Columns.Add(colDecimal);
DataColumn colDataTable = new DataColumn("DataTableCol");
colDataTable.DataType = typeof(DataTable);
myTable.Columns.Add(colDataTable);
DataColumn colArray = new DataColumn("ArrayCol");
colArray.DataType = typeof(int[]);
myTable.Columns.Add(colArray);
DataColumn colBytes = new DataColumn("BytesCol");
colBytes.DataType = typeof(byte[]);
myTable.Columns.Add(colBytes);
// populate one row with values.
DataRow myNewRow = myTable.NewRow();
myNewRow["StringCol"] = "Item Name";
myNewRow["Int32Col"] = 2147483647;
myNewRow["BooleanCol"] = true;
myNewRow["TimeSpanCol"] = new TimeSpan(10, 22, 10, 15, 100);
myNewRow["DateTimeCol"] = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc);
myNewRow["DecimalCol"] = 64.0021;
myNewRow["ArrayCol"] = new[] { 1 };
myNewRow["BytesCol"] = Encoding.UTF8.GetBytes("Hello world");
DataTable nestedTable = new DataTable("Nested");
DataColumn nestedColString = new DataColumn("NestedStringCol");
nestedColString.DataType = typeof(string);
nestedTable.Columns.Add(nestedColString);
DataRow myNewNestedRow = nestedTable.NewRow();
myNewNestedRow["NestedStringCol"] = "Nested!";
nestedTable.Rows.Add(myNewNestedRow);
myNewRow["DataTableCol"] = nestedTable;
myTable.Rows.Add(myNewRow);
string json = JsonConvert.SerializeObject(myTable, Formatting.Indented);
Assert.AreEqual(@"[
{
""StringCol"": ""Item Name"",
""Int32Col"": 2147483647,
""BooleanCol"": true,
""TimeSpanCol"": ""10.22:10:15.1000000"",
""DateTimeCol"": ""2000-12-29T00:00:00Z"",
""DecimalCol"": 64.0021,
""DataTableCol"": [
{
""NestedStringCol"": ""Nested!""
}
],
""ArrayCol"": [
1
],
""BytesCol"": ""SGVsbG8gd29ybGQ=""
}
]", json);
}
public class TestDataTableConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
DataTable d = (DataTable)value;
writer.WriteValue(d.TableName);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
//reader.Read();
DataTable d = new DataTable((string)reader.Value);
return d;
}
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(DataTable));
}
}
[Test]
public void PassedInJsonConverterOverridesInternalConverter()
{
DataTable t1 = new DataTable("Custom");
string json = JsonConvert.SerializeObject(t1, Formatting.Indented, new TestDataTableConverter());
Assert.AreEqual(@"""Custom""", json);
DataTable t2 = JsonConvert.DeserializeObject<DataTable>(json, new TestDataTableConverter());
Assert.AreEqual(t1.TableName, t2.TableName);
}
[Test]
public void SerializeDataTableWithNull()
{
var table = new DataTable();
table.Columns.Add("item");
table.Columns.Add("price", typeof(double));
table.Rows.Add("shirt", 49.99);
table.Rows.Add("pants", 54.99);
table.Rows.Add("shoes"); // no price
var json = JsonConvert.SerializeObject(table);
Assert.AreEqual(@"["
+ @"{""item"":""shirt"",""price"":49.99},"
+ @"{""item"":""pants"",""price"":54.99},"
+ @"{""item"":""shoes"",""price"":null}]", json);
}
[Test]
public void SerializeDataTableWithNullAndIgnoreNullHandling()
{
var table = new DataTable();
table.Columns.Add("item");
table.Columns.Add("price", typeof(double));
table.Rows.Add("shirt", 49.99);
table.Rows.Add("pants", 54.99);
table.Rows.Add("shoes"); // no price
var json = JsonConvert.SerializeObject(table, Formatting.None, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
Assert.AreEqual(@"["
+ @"{""item"":""shirt"",""price"":49.99},"
+ @"{""item"":""pants"",""price"":54.99},"
+ @"{""item"":""shoes""}]", json);
}
[Test]
public void DerializeDataTableWithImplicitNull()
{
const string json = @"["
+ @"{""item"":""shirt"",""price"":49.99},"
+ @"{""item"":""pants"",""price"":54.99},"
+ @"{""item"":""shoes""}]";
var table = JsonConvert.DeserializeObject<DataTable>(json);
Assert.AreEqual("shirt", table.Rows[0]["item"]);
Assert.AreEqual("pants", table.Rows[1]["item"]);
Assert.AreEqual("shoes", table.Rows[2]["item"]);
Assert.AreEqual(49.99, (double)table.Rows[0]["price"], 0.01);
Assert.AreEqual(54.99, (double)table.Rows[1]["price"], 0.01);
CustomAssert.IsInstanceOfType(typeof(System.DBNull), table.Rows[2]["price"]);
}
[Test]
public void DerializeDataTableWithExplicitNull()
{
const string json = @"["
+ @"{""item"":""shirt"",""price"":49.99},"
+ @"{""item"":""pants"",""price"":54.99},"
+ @"{""item"":""shoes"",""price"":null}]";
var table = JsonConvert.DeserializeObject<DataTable>(json);
Assert.AreEqual("shirt", table.Rows[0]["item"]);
Assert.AreEqual("pants", table.Rows[1]["item"]);
Assert.AreEqual("shoes", table.Rows[2]["item"]);
Assert.AreEqual(49.99, (double)table.Rows[0]["price"], 0.01);
Assert.AreEqual(54.99, (double)table.Rows[1]["price"], 0.01);
CustomAssert.IsInstanceOfType(typeof(System.DBNull), table.Rows[2]["price"]);
}
[Test]
public void SerializeKeyValuePairWithDataTableKey()
{
DataTable table = new DataTable();
DataColumn idColumn = new DataColumn("id", typeof(int));
idColumn.AutoIncrement = true;
DataColumn itemColumn = new DataColumn("item");
table.Columns.Add(idColumn);
table.Columns.Add(itemColumn);
DataRow r = table.NewRow();
r["item"] = "item!";
r.EndEdit();
table.Rows.Add(r);
KeyValuePair<DataTable, int> pair = new KeyValuePair<DataTable, int>(table, 1);
string serializedpair = JsonConvert.SerializeObject(pair, Formatting.Indented);
Assert.AreEqual(@"{
""Key"": [
{
""id"": 0,
""item"": ""item!""
}
],
""Value"": 1
}", serializedpair);
var pair2 = (KeyValuePair<DataTable, int>)JsonConvert.DeserializeObject(serializedpair, typeof(KeyValuePair<DataTable, int>));
Assert.AreEqual(1, pair2.Value);
Assert.AreEqual(1, pair2.Key.Rows.Count);
Assert.AreEqual("item!", pair2.Key.Rows[0]["item"]);
}
[Test]
public void SerializedTypedDataTable()
{
CustomerDataSet.CustomersDataTable dt = new CustomerDataSet.CustomersDataTable();
dt.AddCustomersRow("432");
string json = JsonConvert.SerializeObject(dt, Formatting.Indented);
Assert.AreEqual(@"[
{
""CustomerID"": ""432""
}
]", json);
}
[Test]
public void DeserializedTypedDataTable()
{
string json = @"[
{
""CustomerID"": ""432""
}
]";
var dt = JsonConvert.DeserializeObject<CustomerDataSet.CustomersDataTable>(json);
Assert.AreEqual("432", dt[0].CustomerID);
}
}
}
#endif

View File

@@ -0,0 +1,189 @@
#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 || PORTABLE40)
using System;
using System.Collections.Generic;
#if !NET20 && !NETFX_CORE
using System.Data.Linq;
#endif
#if !NETFX_CORE
using System.Data.SqlTypes;
#endif
using System.Dynamic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
#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.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Converters
{
[TestFixture]
public class ExpandoObjectConverterTests : TestFixtureBase
{
public class ExpandoContainer
{
public string Before { get; set; }
public ExpandoObject Expando { get; set; }
public string After { get; set; }
}
[Test]
public void SerializeExpandoObject()
{
ExpandoContainer d = new ExpandoContainer
{
Before = "Before!",
Expando = new ExpandoObject(),
After = "After!"
};
dynamic o = d.Expando;
o.String = "String!";
o.Integer = 234;
o.Float = 1.23d;
o.List = new List<string> { "First", "Second", "Third" };
o.Object = new Dictionary<string, object>
{
{ "First", 1 }
};
string json = JsonConvert.SerializeObject(d, Formatting.Indented);
Assert.AreEqual(@"{
""Before"": ""Before!"",
""Expando"": {
""String"": ""String!"",
""Integer"": 234,
""Float"": 1.23,
""List"": [
""First"",
""Second"",
""Third""
],
""Object"": {
""First"": 1
}
},
""After"": ""After!""
}", json);
}
[Test]
public void SerializeNullExpandoObject()
{
ExpandoContainer d = new ExpandoContainer();
string json = JsonConvert.SerializeObject(d, Formatting.Indented);
Assert.AreEqual(@"{
""Before"": null,
""Expando"": null,
""After"": null
}", json);
}
[Test]
public void DeserializeExpandoObject()
{
string json = @"{
""Before"": ""Before!"",
""Expando"": {
""String"": ""String!"",
""Integer"": 234,
""Float"": 1.23,
""List"": [
""First"",
""Second"",
""Third""
],
""Object"": {
""First"": 1
}
},
""After"": ""After!""
}";
ExpandoContainer o = JsonConvert.DeserializeObject<ExpandoContainer>(json);
Assert.AreEqual(o.Before, "Before!");
Assert.AreEqual(o.After, "After!");
Assert.IsNotNull(o.Expando);
dynamic d = o.Expando;
CustomAssert.IsInstanceOfType(typeof(ExpandoObject), d);
Assert.AreEqual("String!", d.String);
CustomAssert.IsInstanceOfType(typeof(string), d.String);
Assert.AreEqual(234, d.Integer);
CustomAssert.IsInstanceOfType(typeof(long), d.Integer);
Assert.AreEqual(1.23, d.Float);
CustomAssert.IsInstanceOfType(typeof(double), d.Float);
Assert.IsNotNull(d.List);
Assert.AreEqual(3, d.List.Count);
CustomAssert.IsInstanceOfType(typeof(List<object>), d.List);
Assert.AreEqual("First", d.List[0]);
CustomAssert.IsInstanceOfType(typeof(string), d.List[0]);
Assert.AreEqual("Second", d.List[1]);
Assert.AreEqual("Third", d.List[2]);
Assert.IsNotNull(d.Object);
CustomAssert.IsInstanceOfType(typeof(ExpandoObject), d.Object);
Assert.AreEqual(1, d.Object.First);
CustomAssert.IsInstanceOfType(typeof(long), d.Object.First);
}
[Test]
public void DeserializeNullExpandoObject()
{
string json = @"{
""Before"": null,
""Expando"": null,
""After"": null
}";
ExpandoContainer c = JsonConvert.DeserializeObject<ExpandoContainer>(json);
Assert.AreEqual(null, c.Expando);
}
}
}
#endif

View File

@@ -0,0 +1,298 @@
#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
using System;
using Newtonsoft.Json.Tests.TestObjects;
#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.Converters;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Tests.Converters
{
[TestFixture]
public class IsoDateTimeConverterTests : TestFixtureBase
{
[Test]
public void PropertiesShouldBeSet()
{
IsoDateTimeConverter converter = new IsoDateTimeConverter();
Assert.AreEqual(CultureInfo.CurrentCulture, converter.Culture);
Assert.AreEqual(string.Empty, converter.DateTimeFormat);
Assert.AreEqual(DateTimeStyles.RoundtripKind, converter.DateTimeStyles);
converter = new IsoDateTimeConverter()
{
DateTimeFormat = "F",
Culture = CultureInfo.InvariantCulture,
DateTimeStyles = DateTimeStyles.None
};
Assert.AreEqual(CultureInfo.InvariantCulture, converter.Culture);
Assert.AreEqual("F", converter.DateTimeFormat);
Assert.AreEqual(DateTimeStyles.None, converter.DateTimeStyles);
}
public static string GetUtcOffsetText(DateTime d)
{
TimeSpan utcOffset = d.GetUtcOffset();
return utcOffset.Hours.ToString("+00;-00", CultureInfo.InvariantCulture) + ":" + utcOffset.Minutes.ToString("00;00", CultureInfo.InvariantCulture);
}
[Test]
public void SerializeDateTime()
{
IsoDateTimeConverter converter = new IsoDateTimeConverter();
DateTime d = new DateTime(2000, 12, 15, 22, 11, 3, 55, DateTimeKind.Utc);
string result;
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual(@"""2000-12-15T22:11:03.055Z""", result);
Assert.AreEqual(d, JsonConvert.DeserializeObject<DateTime>(result, converter));
d = new DateTime(2000, 12, 15, 22, 11, 3, 55, DateTimeKind.Local);
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual(@"""2000-12-15T22:11:03.055" + GetUtcOffsetText(d) + @"""", result);
}
[Test]
public void SerializeFormattedDateTimeInvariantCulture()
{
IsoDateTimeConverter converter = new IsoDateTimeConverter() { DateTimeFormat = "F", Culture = CultureInfo.InvariantCulture };
DateTime d = new DateTime(2000, 12, 15, 22, 11, 3, 0, DateTimeKind.Utc);
string result;
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual(@"""Friday, 15 December 2000 22:11:03""", result);
Assert.AreEqual(d, JsonConvert.DeserializeObject<DateTime>(result, converter));
d = new DateTime(2000, 12, 15, 22, 11, 3, 0, DateTimeKind.Local);
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual(@"""Friday, 15 December 2000 22:11:03""", result);
}
[Test]
public void SerializeCustomFormattedDateTime()
{
IsoDateTimeConverter converter = new IsoDateTimeConverter
{
DateTimeFormat = "dd/MM/yyyy",
Culture = CultureInfo.InvariantCulture
};
string json = @"""09/12/2006""";
DateTime d = JsonConvert.DeserializeObject<DateTime>(json, converter);
Assert.AreEqual(9, d.Day);
Assert.AreEqual(12, d.Month);
Assert.AreEqual(2006, d.Year);
}
#if !NETFX_CORE
[Test]
public void SerializeFormattedDateTimeNewZealandCulture()
{
IsoDateTimeConverter converter = new IsoDateTimeConverter() { DateTimeFormat = "F", Culture = CultureInfo.GetCultureInfo("en-NZ") };
DateTime d = new DateTime(2000, 12, 15, 22, 11, 3, 0, DateTimeKind.Utc);
string result;
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual(@"""Friday, 15 December 2000 10:11:03 p.m.""", result);
Assert.AreEqual(d, JsonConvert.DeserializeObject<DateTime>(result, converter));
d = new DateTime(2000, 12, 15, 22, 11, 3, 0, DateTimeKind.Local);
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual(@"""Friday, 15 December 2000 10:11:03 p.m.""", result);
}
[Test]
public void SerializeDateTimeCulture()
{
IsoDateTimeConverter converter = new IsoDateTimeConverter() { Culture = CultureInfo.GetCultureInfo("en-NZ") };
string json = @"""09/12/2006""";
DateTime d = JsonConvert.DeserializeObject<DateTime>(json, converter);
Assert.AreEqual(9, d.Day);
Assert.AreEqual(12, d.Month);
Assert.AreEqual(2006, d.Year);
}
#endif
#if !NET20
[Test]
public void SerializeDateTimeOffset()
{
IsoDateTimeConverter converter = new IsoDateTimeConverter();
DateTimeOffset d = new DateTimeOffset(2000, 12, 15, 22, 11, 3, 55, TimeSpan.Zero);
string result;
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual(@"""2000-12-15T22:11:03.055+00:00""", result);
Assert.AreEqual(d, JsonConvert.DeserializeObject<DateTimeOffset>(result, converter));
}
[Test]
public void SerializeUTC()
{
DateTimeTestClass c = new DateTimeTestClass();
c.DateTimeField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
c.DateTimeOffsetField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
c.PreField = "Pre";
c.PostField = "Post";
string json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
Assert.AreEqual(@"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12+00:00"",""PostField"":""Post""}", json);
//test the other edge case too
c.DateTimeField = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc).ToLocalTime();
c.DateTimeOffsetField = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc).ToLocalTime();
c.PreField = "Pre";
c.PostField = "Post";
json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
Assert.AreEqual(@"{""PreField"":""Pre"",""DateTimeField"":""2008-01-01T01:01:01Z"",""DateTimeOffsetField"":""2008-01-01T01:01:01+00:00"",""PostField"":""Post""}", json);
}
[Test]
public void NullableSerializeUTC()
{
NullableDateTimeTestClass c = new NullableDateTimeTestClass();
c.DateTimeField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
c.DateTimeOffsetField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
c.PreField = "Pre";
c.PostField = "Post";
string json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
Assert.AreEqual(@"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12+00:00"",""PostField"":""Post""}", json);
//test the other edge case too
c.DateTimeField = null;
c.DateTimeOffsetField = null;
c.PreField = "Pre";
c.PostField = "Post";
json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
Assert.AreEqual(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", json);
}
[Test]
public void NullableDeserializeEmptyString()
{
string json = @"{""DateTimeField"":""""}";
NullableDateTimeTestClass c = JsonConvert.DeserializeObject<NullableDateTimeTestClass>(json,
new JsonSerializerSettings { Converters = new[] { new IsoDateTimeConverter() } });
Assert.AreEqual(null, c.DateTimeField);
}
[Test]
public void DeserializeNullToNonNullable()
{
ExceptionAssert.Throws<JsonSerializationException>("Cannot convert null value to System.DateTime. Path 'DateTimeField', line 1, position 38.",
() =>
{
DateTimeTestClass c2 =
JsonConvert.DeserializeObject<DateTimeTestClass>(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
});
}
[Test]
public void SerializeShouldChangeNonUTCDates()
{
DateTime localDateTime = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Local);
DateTimeTestClass c = new DateTimeTestClass();
c.DateTimeField = localDateTime;
c.PreField = "Pre";
c.PostField = "Post";
string json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal }); //note that this fails without the Utc converter...
c.DateTimeField = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc);
string json2 = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
TimeSpan offset = localDateTime.GetUtcOffset();
// if the current timezone is utc then local already equals utc
if (offset == TimeSpan.Zero)
Assert.AreEqual(json, json2);
else
Assert.AreNotEqual(json, json2);
}
#endif
[Test]
public void BlogCodeSample()
{
Person p = new Person
{
Name = "Keith",
BirthDate = new DateTime(1980, 3, 8),
LastModified = new DateTime(2009, 4, 12, 20, 44, 55),
};
string jsonText = JsonConvert.SerializeObject(p, new IsoDateTimeConverter());
// {
// "Name": "Keith",
// "BirthDate": "1980-03-08T00:00:00",
// "LastModified": "2009-04-12T20:44:55"
// }
Console.WriteLine(jsonText);
}
#if !NET20
[Test]
public void DeserializeDateTimeOffset()
{
var settings = new JsonSerializerSettings();
settings.DateParseHandling = DateParseHandling.DateTimeOffset;
settings.Converters.Add(new IsoDateTimeConverter());
// Intentionally use an offset that is unlikely in the real world,
// so the test will be accurate regardless of the local time zone setting.
var offset = new TimeSpan(2, 15, 0);
var dto = new DateTimeOffset(2014, 1, 1, 0, 0, 0, 0, offset);
var test = JsonConvert.DeserializeObject<DateTimeOffset>("\"2014-01-01T00:00:00+02:15\"", settings);
Assert.AreEqual(dto, test);
Assert.AreEqual(dto.ToString("o"), test.ToString("o"));
}
#endif
}
}

View File

@@ -0,0 +1,249 @@
#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
using System;
using System.Collections.Generic;
#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.Converters;
using Newtonsoft.Json.Tests.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Converters
{
[TestFixture]
public class JavaScriptDateTimeConverterTests : TestFixtureBase
{
[Test]
public void SerializeDateTime()
{
JavaScriptDateTimeConverter converter = new JavaScriptDateTimeConverter();
DateTime d = new DateTime(2000, 12, 15, 22, 11, 3, 55, DateTimeKind.Utc);
string result;
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual("new Date(976918263055)", result);
}
#if !NET20
[Test]
public void SerializeDateTimeOffset()
{
JavaScriptDateTimeConverter converter = new JavaScriptDateTimeConverter();
DateTimeOffset now = new DateTimeOffset(2000, 12, 15, 22, 11, 3, 55, TimeSpan.Zero);
string result;
result = JsonConvert.SerializeObject(now, converter);
Assert.AreEqual("new Date(976918263055)", result);
}
[Test]
public void sdfs()
{
int i = Convert.ToInt32("+1");
Console.WriteLine(i);
}
[Test]
public void SerializeNullableDateTimeClass()
{
NullableDateTimeTestClass t = new NullableDateTimeTestClass()
{
DateTimeField = null,
DateTimeOffsetField = null
};
JavaScriptDateTimeConverter converter = new JavaScriptDateTimeConverter();
string result;
result = JsonConvert.SerializeObject(t, converter);
Assert.AreEqual(@"{""PreField"":null,""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":null}", result);
t = new NullableDateTimeTestClass()
{
DateTimeField = new DateTime(2000, 12, 15, 22, 11, 3, 55, DateTimeKind.Utc),
DateTimeOffsetField = new DateTimeOffset(2000, 12, 15, 22, 11, 3, 55, TimeSpan.Zero)
};
result = JsonConvert.SerializeObject(t, converter);
Assert.AreEqual(@"{""PreField"":null,""DateTimeField"":new Date(976918263055),""DateTimeOffsetField"":new Date(976918263055),""PostField"":null}", result);
}
[Test]
public void DeserializeNullToNonNullable()
{
ExceptionAssert.Throws<Exception>("Cannot convert null value to System.DateTime. Path 'DateTimeField', line 1, position 38.",
() =>
{
DateTimeTestClass c2 =
JsonConvert.DeserializeObject<DateTimeTestClass>(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", new JavaScriptDateTimeConverter());
});
}
[Test]
public void DeserializeDateTimeOffset()
{
JavaScriptDateTimeConverter converter = new JavaScriptDateTimeConverter();
DateTimeOffset start = new DateTimeOffset(2000, 12, 15, 22, 11, 3, 55, TimeSpan.Zero);
string json = JsonConvert.SerializeObject(start, converter);
DateTimeOffset result = JsonConvert.DeserializeObject<DateTimeOffset>(json, converter);
Assert.AreEqual(new DateTimeOffset(2000, 12, 15, 22, 11, 3, 55, TimeSpan.Zero), result);
}
#endif
[Test]
public void DeserializeDateTime()
{
JavaScriptDateTimeConverter converter = new JavaScriptDateTimeConverter();
DateTime result = JsonConvert.DeserializeObject<DateTime>("new Date(976918263055)", converter);
Assert.AreEqual(new DateTime(2000, 12, 15, 22, 11, 3, 55, DateTimeKind.Utc), result);
}
[Test]
public void ConverterList()
{
ConverterList<object> l1 = new ConverterList<object>();
l1.Add(new DateTime(2000, 12, 12, 20, 10, 0, DateTimeKind.Utc));
l1.Add(new DateTime(1983, 10, 9, 23, 10, 0, DateTimeKind.Utc));
string json = JsonConvert.SerializeObject(l1, Formatting.Indented);
Assert.AreEqual(@"[
new Date(
976651800000
),
new Date(
434589000000
)
]", json);
ConverterList<object> l2 = JsonConvert.DeserializeObject<ConverterList<object>>(json);
Assert.IsNotNull(l2);
Assert.AreEqual(new DateTime(2000, 12, 12, 20, 10, 0, DateTimeKind.Utc), l2[0]);
Assert.AreEqual(new DateTime(1983, 10, 9, 23, 10, 0, DateTimeKind.Utc), l2[1]);
}
[Test]
public void ConverterDictionary()
{
ConverterDictionary<object> l1 = new ConverterDictionary<object>();
l1.Add("First", new DateTime(2000, 12, 12, 20, 10, 0, DateTimeKind.Utc));
l1.Add("Second", new DateTime(1983, 10, 9, 23, 10, 0, DateTimeKind.Utc));
string json = JsonConvert.SerializeObject(l1, Formatting.Indented);
Assert.AreEqual(@"{
""First"": new Date(
976651800000
),
""Second"": new Date(
434589000000
)
}", json);
ConverterDictionary<object> l2 = JsonConvert.DeserializeObject<ConverterDictionary<object>>(json);
Assert.IsNotNull(l2);
Assert.AreEqual(new DateTime(2000, 12, 12, 20, 10, 0, DateTimeKind.Utc), l2["First"]);
Assert.AreEqual(new DateTime(1983, 10, 9, 23, 10, 0, DateTimeKind.Utc), l2["Second"]);
}
[Test]
public void ConverterObject()
{
ConverterObject l1 = new ConverterObject();
l1.Object1 = new DateTime(2000, 12, 12, 20, 10, 0, DateTimeKind.Utc);
l1.Object2 = null;
l1.ObjectNotHandled = new DateTime(2000, 12, 12, 20, 10, 0, DateTimeKind.Utc);
string json = JsonConvert.SerializeObject(l1, Formatting.Indented);
Assert.AreEqual(@"{
""Object1"": new Date(
976651800000
),
""Object2"": null,
""ObjectNotHandled"": 631122486000000000
}", json);
ConverterObject l2 = JsonConvert.DeserializeObject<ConverterObject>(json);
Assert.IsNotNull(l2);
//Assert.AreEqual(new DateTime(2000, 12, 12, 20, 10, 0, DateTimeKind.Utc), l2["First"]);
//Assert.AreEqual(new DateTime(1983, 10, 9, 23, 10, 0, DateTimeKind.Utc), l2["Second"]);
}
}
[JsonArray(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
public class ConverterList<T> : List<T>
{
}
[JsonDictionary(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
public class ConverterDictionary<T> : Dictionary<string, T>
{
}
[JsonObject(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
public class ConverterObject
{
public object Object1 { get; set; }
public object Object2 { get; set; }
[JsonConverter(typeof(DateIntConverter))]
public object ObjectNotHandled { get; set; }
}
public class DateIntConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
DateTime? d = (DateTime?)value;
if (d == null)
writer.WriteNull();
else
writer.WriteValue(d.Value.Ticks);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return new DateTime(Convert.ToInt64(reader.Value), DateTimeKind.Utc);
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime) || objectType == typeof(DateTime?);
}
}
}

View File

@@ -0,0 +1,457 @@
#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 NETFX_CORE
using System;
using Newtonsoft.Json.Converters;
#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 Windows.Data.Json;
using System.IO;
using System.Diagnostics;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
namespace Newtonsoft.Json.Tests.Converters
{
[TestFixture]
public class JsonValueConverterTests : TestFixtureBase
{
public class Computer
{
public string Cpu { get; set; }
public List<string> Drives { get; set; }
}
[Test]
public void WriteJson()
{
JsonObject o = JsonObject.Parse(@"{
""CPU"": ""Intel"",
""Drives"": [
""DVD read/writer"",
""500 gigabyte hard drive""
]
}");
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
JsonValueConverter converter = new JsonValueConverter();
converter.WriteJson(writer, o, null);
string json = sw.ToString();
Assert.AreEqual(@"{""Drives"":[""DVD read/writer"",""500 gigabyte hard drive""],""CPU"":""Intel""}", json);
}
[Test]
public void ReadJson()
{
string json = @"{
""CPU"": ""Intel"",
""Drives"": [
""DVD read/writer"",
""500 gigabyte hard drive""
]
}";
JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter();
JsonObject o = (JsonObject)converter.ReadJson(writer, typeof(JsonObject), null, null);
Assert.AreEqual(2, o.Count);
Assert.AreEqual("Intel", o.GetNamedString("CPU"));
Assert.AreEqual("DVD read/writer", o.GetNamedArray("Drives")[0].GetString());
Assert.AreEqual("500 gigabyte hard drive", o.GetNamedArray("Drives")[1].GetString());
}
[Test]
public void ReadJsonComments()
{
string json = @"{/*comment!*/
""CPU"": ""Intel"",/*comment!*/
""Drives"": [/*comment!*/
""DVD read/writer"",
/*comment!*/""500 gigabyte hard drive""
]/*comment!*/
}";
JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter();
JsonObject o = (JsonObject)converter.ReadJson(writer, typeof(JsonObject), null, null);
Assert.AreEqual(2, o.Count);
Assert.AreEqual("Intel", o.GetNamedString("CPU"));
Assert.AreEqual("DVD read/writer", o.GetNamedArray("Drives")[0].GetString());
Assert.AreEqual("500 gigabyte hard drive", o.GetNamedArray("Drives")[1].GetString());
}
[Test]
public void ReadJsonNullValue()
{
string json = "null";
JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter();
JsonValue v = (JsonValue)converter.ReadJson(writer, typeof(JsonValue), null, null);
Assert.AreEqual(JsonValueType.Null, v.ValueType);
}
[Test]
public void ReadJsonUnsupportedValue()
{
string json = "undefined";
JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter();
ExceptionAssert.Throws<JsonException>("Unexpected or unsupported token: Undefined. Path '', line 1, position 9.",
() =>
{
converter.ReadJson(writer, typeof(JsonValue), null, null);
});
}
[Test]
public void ReadJsonUnexpectedEndInArray()
{
string json = "[";
JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter();
ExceptionAssert.Throws<JsonException>("Unexpected end. Path '', line 1, position 1.",
() =>
{
converter.ReadJson(writer, typeof(JsonValue), null, null);
});
}
[Test]
public void ReadJsonUnexpectedEndAfterComment()
{
string json = "[/*comment!*/";
JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter();
ExceptionAssert.Throws<JsonException>("Unexpected end. Path '', line 1, position 13.",
() =>
{
converter.ReadJson(writer, typeof(JsonValue), null, null);
});
}
[Test]
public void ReadJsonUnexpectedEndInObject()
{
string json = "{'hi':";
JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter();
ExceptionAssert.Throws<JsonException>("Unexpected end. Path 'hi', line 1, position 6.",
() =>
{
converter.ReadJson(writer, typeof(JsonValue), null, null);
});
}
[Test]
public void ReadJsonBadJsonType()
{
string json = "null";
JsonTextReader writer = new JsonTextReader(new StringReader(json));
JsonValueConverter converter = new JsonValueConverter();
ExceptionAssert.Throws<JsonException>("Could not convert 'Windows.Data.Json.JsonValue' to 'Windows.Data.Json.JsonObject'. Path '', line 1, position 4.",
() =>
{
converter.ReadJson(writer, typeof(JsonObject), null, null);
});
}
[Test]
public void JsonConvertDeserialize()
{
string json = @"[
""DVD read/writer"",
""500 gigabyte hard drive""
]";
JsonArray a = JsonConvert.DeserializeObject<JsonArray>(json);
Assert.AreEqual(2, a.Count);
Assert.AreEqual("DVD read/writer", a[0].GetString());
Assert.AreEqual("500 gigabyte hard drive", a[1].GetString());
}
[Test]
public void JsonConvertSerialize()
{
JsonArray a = JsonArray.Parse(@"[
""DVD read/writer"",
""500 gigabyte hard drive""
]");
string json = JsonConvert.SerializeObject(a, Formatting.Indented);
Assert.AreEqual(@"[
""DVD read/writer"",
""500 gigabyte hard drive""
]", json);
}
[Test]
public void SerializeDouble()
{
JsonObject o = new JsonObject();
o["zero"] = JsonValue.CreateNumberValue(0);
o["int"] = JsonValue.CreateNumberValue(1);
o["smallfraction"] = JsonValue.CreateNumberValue(3.0000000000000009);
o["double"] = JsonValue.CreateNumberValue(1.1);
o["probablyint"] = JsonValue.CreateNumberValue(1.0);
o["Epsilon"] = JsonValue.CreateNumberValue(double.Epsilon);
o["MinValue"] = JsonValue.CreateNumberValue(double.MinValue);
o["MaxValue"] = JsonValue.CreateNumberValue(double.MaxValue);
o["NaN"] = JsonValue.CreateNumberValue(double.NaN);
o["NegativeInfinity"] = JsonValue.CreateNumberValue(double.NegativeInfinity);
o["PositiveInfinity"] = JsonValue.CreateNumberValue(double.PositiveInfinity);
string json = JsonConvert.SerializeObject(o, Formatting.Indented);
Assert.AreEqual(@"{
""PositiveInfinity"": ""Infinity"",
""NegativeInfinity"": ""-Infinity"",
""MinValue"": -1.7976931348623157E+308,
""double"": 1.1,
""int"": 1,
""zero"": 0,
""Epsilon"": 4.94065645841247E-324,
""MaxValue"": 1.7976931348623157E+308,
""NaN"": ""NaN"",
""smallfraction"": 3.0000000000000009,
""probablyint"": 1
}", json);
}
[Test]
public void DeserializePerformance()
{
string json = @"{
""CPU"": ""Intel"",
""Drives"": [
""DVD read/writer"",
""500 gigabyte hard drive""
]
}";
Stopwatch timer = new Stopwatch();
timer.Start();
for (int i = 0; i < 100000; i++)
{
JsonObject o = JsonObject.Parse(json);
}
timer.Stop();
string winrt = timer.Elapsed.TotalSeconds.ToString();
timer = new Stopwatch();
timer.Start();
for (int i = 0; i < 100000; i++)
{
JObject o = JObject.Parse(json);
}
timer.Stop();
string linq = timer.Elapsed.TotalSeconds.ToString();
// warm up
JsonConvert.DeserializeObject<Computer>(json);
timer = new Stopwatch();
timer.Start();
for (int i = 0; i < 100000; i++)
{
Computer o = JsonConvert.DeserializeObject<Computer>(json);
}
timer.Stop();
string jsonnet = timer.Elapsed.TotalSeconds.ToString();
throw new Exception(string.Format("winrt: {0}, jsonnet: {1}, jsonnet linq: {2}", winrt, jsonnet, linq));
}
[Test]
public void SerializePerformance()
{
string json = @"{
""CPU"": ""Intel"",
""Drives"": [
""DVD read/writer"",
""500 gigabyte hard drive""
]
}";
JsonObject o = JsonObject.Parse(json);
JObject o1 = JObject.Parse(json);
Computer o2 = JsonConvert.DeserializeObject<Computer>(json);
Stopwatch timer = new Stopwatch();
timer.Start();
for (int i = 0; i < 100000; i++)
{
o.Stringify();
}
timer.Stop();
string winrt = timer.Elapsed.TotalSeconds.ToString();
timer.Start();
for (int i = 0; i < 100000; i++)
{
o1.ToString(Formatting.None);
}
timer.Stop();
string linq = timer.Elapsed.TotalSeconds.ToString();
timer = new Stopwatch();
timer.Start();
for (int i = 0; i < 100000; i++)
{
JsonConvert.SerializeObject(o);
}
timer.Stop();
string jsonnet = timer.Elapsed.TotalSeconds.ToString();
throw new Exception(string.Format("winrt: {0}, jsonnet: {1}, jsonnet linq: {2}", winrt, jsonnet, linq));
}
[Test]
public void ParseJson()
{
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""
]
}
]
}
}";
// Windows.Data.Json
// -----------------
JsonObject jsonObject = JsonObject.Parse(json);
string itemTitle1 = jsonObject["channel"].GetObject()["item"].GetArray()[0].GetObject()["title"].GetString();
// LINQ to JSON
// ------------
JObject jObject = JObject.Parse(json);
string itemTitle2 = (string)jObject["channel"]["item"][0]["title"];
}
[Test]
public void CreateJson()
{
// Windows.Data.Json
// -----------------
JsonObject jsonObject = new JsonObject
{
{"CPU", JsonValue.CreateStringValue("Intel")},
{"Drives", new JsonArray {
JsonValue.CreateStringValue("DVD read/writer"),
JsonValue.CreateStringValue("500 gigabyte hard drive")
}
}
};
string json1 = jsonObject.Stringify();
// LINQ to JSON
// ------------
JObject jObject = new JObject
{
{"CPU", "Intel"},
{"Drives", new JArray {
"DVD read/writer",
"500 gigabyte hard drive"
}
}
};
string json2 = jObject.ToString();
}
[Test]
public void Converting()
{
JsonObject jsonObject = new JsonObject
{
{"CPU", JsonValue.CreateStringValue("Intel")},
{"Drives", new JsonArray {
JsonValue.CreateStringValue("DVD read/writer"),
JsonValue.CreateStringValue("500 gigabyte hard drive")
}
}
};
// convert Windows.Data.Json to LINQ to JSON
JObject o = JObject.FromObject(jsonObject);
// convert LINQ to JSON to Windows.Data.Json
JArray a = (JArray)o["Drives"];
JsonArray jsonArray = a.ToObject<JsonArray>();
}
}
}
#endif

View File

@@ -0,0 +1,87 @@
#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
using System.IO;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Utilities;
#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
namespace Newtonsoft.Json.Tests.Converters
{
[TestFixture]
public class ObjectIdConverterTests : TestFixtureBase
{
public class ObjectIdTestClass
{
[JsonProperty("_id")]
public BsonObjectId Id { get; set; }
[JsonProperty("test")]
public string Test { get; set; }
}
[Test]
public void Serialize()
{
ObjectIdTestClass c = new ObjectIdTestClass
{
Id = new BsonObjectId(HexToBytes("4ABBED9D1D8B0F0218000001")),
Test = "1234£56"
};
MemoryStream ms = new MemoryStream();
JsonSerializer serializer = new JsonSerializer();
// serialize product to BSON
BsonWriter writer = new BsonWriter(ms);
serializer.Serialize(writer, c);
byte[] expected = HexToBytes("29000000075F6964004ABBED9D1D8B0F02180000010274657374000900000031323334C2A335360000");
CollectionAssert.AreEquivalent(expected, ms.ToArray());
}
[Test]
public void Deserialize()
{
byte[] bson = HexToBytes("29000000075F6964004ABBED9D1D8B0F02180000010274657374000900000031323334C2A335360000");
JsonSerializer serializer = new JsonSerializer();
BsonReader reader = new BsonReader(new MemoryStream(bson));
ObjectIdTestClass c = serializer.Deserialize<ObjectIdTestClass>(reader);
CollectionAssert.AreEquivalent(c.Id.Value, HexToBytes("4ABBED9D1D8B0F0218000001"));
Assert.AreEqual(c.Test, "1234£56");
}
}
}

View File

@@ -0,0 +1,238 @@
#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
using System;
using System.Collections.Generic;
#if !NET20 && !NETFX_CORE
using System.Data.Linq;
#endif
#if !NETFX_CORE
using System.Data.SqlTypes;
#endif
using System.IO;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
#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.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Converters
{
[TestFixture]
public class RegexConverterTests : TestFixtureBase
{
public class RegexTestClass
{
public Regex Regex { get; set; }
}
[Test]
public void SerializeToText()
{
Regex regex = new Regex("abc", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
string json = JsonConvert.SerializeObject(regex, Formatting.Indented, new RegexConverter());
Assert.AreEqual(@"{
""Pattern"": ""abc"",
""Options"": 513
}", json);
}
[Test]
public void SerializeCamelCaseAndStringEnums()
{
Regex regex = new Regex("abc", RegexOptions.IgnoreCase);
string json = JsonConvert.SerializeObject(regex, Formatting.Indented, new JsonSerializerSettings
{
Converters = { new RegexConverter(), new StringEnumConverter() { CamelCaseText = true } },
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(@"{
""pattern"": ""abc"",
""options"": ""ignoreCase""
}", json);
}
[Test]
public void DeserializeCamelCaseAndStringEnums()
{
string json = @"{
""pattern"": ""abc"",
""options"": ""ignoreCase""
}";
Regex regex = JsonConvert.DeserializeObject<Regex>(json, new JsonSerializerSettings
{
Converters = { new RegexConverter() }
});
Assert.AreEqual("abc", regex.ToString());
Assert.AreEqual(RegexOptions.IgnoreCase, regex.Options);
}
[Test]
public void DeserializeISerializeRegexJson()
{
string json = @"{
""Regex"": {
""pattern"": ""(hi)"",
""options"": 5,
""matchTimeout"": -10000
}
}";
RegexTestClass r = JsonConvert.DeserializeObject<RegexTestClass>(json);
Assert.AreEqual("(hi)", r.Regex.ToString());
Assert.AreEqual(RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture, r.Regex.Options);
}
[Test]
public void SerializeToBson()
{
Regex regex = new Regex("abc", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new RegexConverter());
serializer.Serialize(writer, new RegexTestClass { Regex = regex });
string expected = "13-00-00-00-0B-52-65-67-65-78-00-61-62-63-00-69-75-00-00";
string bson = BytesToHex(ms.ToArray());
Assert.AreEqual(expected, bson);
}
[Test]
public void DeserializeFromText()
{
string json = @"{
""Pattern"": ""abc"",
""Options"": 513
}";
Regex newRegex = JsonConvert.DeserializeObject<Regex>(json, new RegexConverter());
Assert.AreEqual("abc", newRegex.ToString());
Assert.AreEqual(RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, newRegex.Options);
}
[Test]
public void DeserializeFromBson()
{
MemoryStream ms = new MemoryStream(HexToBytes("13-00-00-00-0B-52-65-67-65-78-00-61-62-63-00-69-75-00-00"));
BsonReader reader = new BsonReader(ms);
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new RegexConverter());
RegexTestClass c = serializer.Deserialize<RegexTestClass>(reader);
Assert.AreEqual("abc", c.Regex.ToString());
Assert.AreEqual(RegexOptions.IgnoreCase, c.Regex.Options);
}
[Test]
public void ConvertEmptyRegexBson()
{
Regex regex = new Regex(string.Empty);
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new RegexConverter());
serializer.Serialize(writer, new RegexTestClass { Regex = regex });
ms.Seek(0, SeekOrigin.Begin);
BsonReader reader = new BsonReader(ms);
serializer.Converters.Add(new RegexConverter());
RegexTestClass c = serializer.Deserialize<RegexTestClass>(reader);
Assert.AreEqual("", c.Regex.ToString());
Assert.AreEqual(RegexOptions.None, c.Regex.Options);
}
[Test]
public void ConvertRegexWithAllOptionsBson()
{
Regex regex = new Regex(
"/",
RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.ExplicitCapture);
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new RegexConverter());
serializer.Serialize(writer, new RegexTestClass { Regex = regex });
string expected = "14-00-00-00-0B-52-65-67-65-78-00-2F-00-69-6D-73-75-78-00-00";
string bson = BytesToHex(ms.ToArray());
Assert.AreEqual(expected, bson);
ms.Seek(0, SeekOrigin.Begin);
BsonReader reader = new BsonReader(ms);
serializer.Converters.Add(new RegexConverter());
RegexTestClass c = serializer.Deserialize<RegexTestClass>(reader);
Assert.AreEqual("/", c.Regex.ToString());
Assert.AreEqual(RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.ExplicitCapture, c.Regex.Options);
}
[Test]
public void ConvertEmptyRegexJson()
{
Regex regex = new Regex("");
string json = JsonConvert.SerializeObject(new RegexTestClass { Regex = regex }, Formatting.Indented, new RegexConverter());
Assert.AreEqual(@"{
""Regex"": {
""Pattern"": """",
""Options"": 0
}
}", json);
RegexTestClass newRegex = JsonConvert.DeserializeObject<RegexTestClass>(json, new RegexConverter());
Assert.AreEqual("", newRegex.Regex.ToString());
Assert.AreEqual(RegexOptions.None, newRegex.Regex.Options);
}
}
}

View File

@@ -0,0 +1,472 @@
#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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Converters;
#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.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Converters
{
[TestFixture]
public class StringEnumConverterTests : TestFixtureBase
{
public class EnumClass
{
public StoreColor StoreColor { get; set; }
public StoreColor? NullableStoreColor1 { get; set; }
public StoreColor? NullableStoreColor2 { get; set; }
}
public class EnumContainer<T>
{
public T Enum { get; set; }
}
[Flags]
public enum FlagsTestEnum
{
Default = 0,
First = 1,
Second = 2
}
public enum NegativeEnum
{
Negative = -1,
Zero = 0,
Positive = 1
}
#if !NET20
public enum NamedEnum
{
[EnumMember(Value = "@first")]
First,
[EnumMember(Value = "@second")]
Second,
Third
}
public enum NamedEnumDuplicate
{
[EnumMember(Value = "Third")]
First,
[EnumMember(Value = "@second")]
Second,
Third
}
#endif
public class NegativeEnumClass
{
public NegativeEnum Value1 { get; set; }
public NegativeEnum Value2 { get; set; }
}
#if !NET20
[Test]
public void NamedEnumDuplicateTest()
{
ExceptionAssert.Throws<Exception>("Enum name 'Third' already exists on enum 'NamedEnumDuplicate'.",
() =>
{
EnumContainer<NamedEnumDuplicate> c = new EnumContainer<NamedEnumDuplicate>
{
Enum = NamedEnumDuplicate.First
};
JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter());
});
}
[Test]
public void SerializeNameEnumTest()
{
EnumContainer<NamedEnum> c = new EnumContainer<NamedEnum>
{
Enum = NamedEnum.First
};
string json = JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter());
Assert.AreEqual(@"{
""Enum"": ""@first""
}", json);
c = new EnumContainer<NamedEnum>
{
Enum = NamedEnum.Third
};
json = JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter());
Assert.AreEqual(@"{
""Enum"": ""Third""
}", json);
}
[Test]
public void DeserializeNameEnumTest()
{
string json = @"{
""Enum"": ""@first""
}";
EnumContainer<NamedEnum> c = JsonConvert.DeserializeObject<EnumContainer<NamedEnum>>(json, new StringEnumConverter());
Assert.AreEqual(NamedEnum.First, c.Enum);
json = @"{
""Enum"": ""Third""
}";
c = JsonConvert.DeserializeObject<EnumContainer<NamedEnum>>(json, new StringEnumConverter());
Assert.AreEqual(NamedEnum.Third, c.Enum);
}
#endif
[Test]
public void SerializeEnumClass()
{
EnumClass enumClass = new EnumClass();
enumClass.StoreColor = StoreColor.Red;
enumClass.NullableStoreColor1 = StoreColor.White;
enumClass.NullableStoreColor2 = null;
string json = JsonConvert.SerializeObject(enumClass, Formatting.Indented, new StringEnumConverter());
Assert.AreEqual(@"{
""StoreColor"": ""Red"",
""NullableStoreColor1"": ""White"",
""NullableStoreColor2"": null
}", json);
}
[Test]
public void SerializeEnumClassWithCamelCase()
{
EnumClass enumClass = new EnumClass();
enumClass.StoreColor = StoreColor.Red;
enumClass.NullableStoreColor1 = StoreColor.DarkGoldenrod;
enumClass.NullableStoreColor2 = null;
string json = JsonConvert.SerializeObject(enumClass, Formatting.Indented, new StringEnumConverter { CamelCaseText = true });
Assert.AreEqual(@"{
""StoreColor"": ""red"",
""NullableStoreColor1"": ""darkGoldenrod"",
""NullableStoreColor2"": null
}", json);
}
[Test]
public void SerializeEnumClassUndefined()
{
EnumClass enumClass = new EnumClass();
enumClass.StoreColor = (StoreColor)1000;
enumClass.NullableStoreColor1 = (StoreColor)1000;
enumClass.NullableStoreColor2 = null;
string json = JsonConvert.SerializeObject(enumClass, Formatting.Indented, new StringEnumConverter());
Assert.AreEqual(@"{
""StoreColor"": 1000,
""NullableStoreColor1"": 1000,
""NullableStoreColor2"": null
}", json);
}
[Test]
public void SerializeFlagEnum()
{
EnumClass enumClass = new EnumClass();
enumClass.StoreColor = StoreColor.Red | StoreColor.White;
enumClass.NullableStoreColor1 = StoreColor.White & StoreColor.Yellow;
enumClass.NullableStoreColor2 = StoreColor.Red | StoreColor.White | StoreColor.Black;
string json = JsonConvert.SerializeObject(enumClass, Formatting.Indented, new StringEnumConverter());
Assert.AreEqual(@"{
""StoreColor"": ""Red, White"",
""NullableStoreColor1"": 0,
""NullableStoreColor2"": ""Black, Red, White""
}", json);
}
[Test]
public void SerializeNegativeEnum()
{
NegativeEnumClass negativeEnumClass = new NegativeEnumClass();
negativeEnumClass.Value1 = NegativeEnum.Negative;
negativeEnumClass.Value2 = (NegativeEnum)int.MinValue;
string json = JsonConvert.SerializeObject(negativeEnumClass, Formatting.Indented, new StringEnumConverter());
Assert.AreEqual(@"{
""Value1"": ""Negative"",
""Value2"": -2147483648
}", json);
}
[Test]
public void DeserializeNegativeEnum()
{
string json = @"{
""Value1"": ""Negative"",
""Value2"": -2147483648
}";
NegativeEnumClass negativeEnumClass = JsonConvert.DeserializeObject<NegativeEnumClass>(json, new StringEnumConverter());
Assert.AreEqual(NegativeEnum.Negative, negativeEnumClass.Value1);
Assert.AreEqual((NegativeEnum)int.MinValue, negativeEnumClass.Value2);
}
[Test]
public void DeserializeFlagEnum()
{
string json = @"{
""StoreColor"": ""Red, White"",
""NullableStoreColor1"": 0,
""NullableStoreColor2"": ""black, Red, White""
}";
EnumClass enumClass = JsonConvert.DeserializeObject<EnumClass>(json, new StringEnumConverter());
Assert.AreEqual(StoreColor.Red | StoreColor.White, enumClass.StoreColor);
Assert.AreEqual((StoreColor)0, enumClass.NullableStoreColor1);
Assert.AreEqual(StoreColor.Red | StoreColor.White | StoreColor.Black, enumClass.NullableStoreColor2);
}
[Test]
public void DeserializeEnumClass()
{
string json = @"{
""StoreColor"": ""Red"",
""NullableStoreColor1"": ""White"",
""NullableStoreColor2"": null
}";
EnumClass enumClass = JsonConvert.DeserializeObject<EnumClass>(json, new StringEnumConverter());
Assert.AreEqual(StoreColor.Red, enumClass.StoreColor);
Assert.AreEqual(StoreColor.White, enumClass.NullableStoreColor1);
Assert.AreEqual(null, enumClass.NullableStoreColor2);
}
[Test]
public void DeserializeEnumClassUndefined()
{
string json = @"{
""StoreColor"": 1000,
""NullableStoreColor1"": 1000,
""NullableStoreColor2"": null
}";
EnumClass enumClass = JsonConvert.DeserializeObject<EnumClass>(json, new StringEnumConverter());
Assert.AreEqual((StoreColor)1000, enumClass.StoreColor);
Assert.AreEqual((StoreColor)1000, enumClass.NullableStoreColor1);
Assert.AreEqual(null, enumClass.NullableStoreColor2);
}
[Test]
public void CamelCaseTextFlagEnumSerialization()
{
EnumContainer<FlagsTestEnum> c = new EnumContainer<FlagsTestEnum>
{
Enum = FlagsTestEnum.First | FlagsTestEnum.Second
};
string json = JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter { CamelCaseText = true });
Assert.AreEqual(@"{
""Enum"": ""first, second""
}", json);
}
[Test]
public void CamelCaseTextFlagEnumDeserialization()
{
string json = @"{
""Enum"": ""first, second""
}";
EnumContainer<FlagsTestEnum> c = JsonConvert.DeserializeObject<EnumContainer<FlagsTestEnum>>(json, new StringEnumConverter { CamelCaseText = true });
Assert.AreEqual(FlagsTestEnum.First | FlagsTestEnum.Second, c.Enum);
}
[Test]
public void DeserializeEmptyStringIntoNullable()
{
string json = @"{
""StoreColor"": ""Red"",
""NullableStoreColor1"": ""White"",
""NullableStoreColor2"": """"
}";
EnumClass c = JsonConvert.DeserializeObject<EnumClass>(json, new StringEnumConverter());
Assert.IsNull(c.NullableStoreColor2);
}
[Test]
public void DeserializeInvalidString()
{
string json = "{ \"Value\" : \"Three\" }";
ExceptionAssert.Throws<JsonSerializationException>(
@"Error converting value ""Three"" to type 'Newtonsoft.Json.Tests.Converters.StringEnumConverterTests+MyEnum'. Path 'Value', line 1, position 19.",
() =>
{
var serializer = new JsonSerializer();
serializer.Converters.Add(new StringEnumConverter());
serializer.Deserialize<Bucket>(new JsonTextReader(new StringReader(json)));
});
}
public class Bucket
{
public MyEnum Value;
}
public enum MyEnum
{
Alpha,
Beta,
}
[Test]
public void DeserializeIntegerButNotAllowed()
{
string json = "{ \"Value\" : 123 }";
try
{
var serializer = new JsonSerializer();
serializer.Converters.Add(new StringEnumConverter { AllowIntegerValues = false });
serializer.Deserialize<Bucket>(new JsonTextReader(new StringReader(json)));
}
catch (JsonSerializationException ex)
{
Assert.AreEqual("Error converting value 123 to type 'Newtonsoft.Json.Tests.Converters.StringEnumConverterTests+MyEnum'. Path 'Value', line 1, position 15.", ex.Message);
Assert.AreEqual(@"Integer value 123 is not allowed. Path 'Value', line 1, position 15.", ex.InnerException.Message);
return;
}
Assert.Fail();
}
#if !NET20
[Test]
public void EnumMemberPlusFlags()
{
List<Foo> lfoo =
new List<Foo>
{
Foo.Bat | Foo.SerializeAsBaz,
Foo.FooBar,
Foo.Bat,
Foo.SerializeAsBaz,
Foo.FooBar | Foo.SerializeAsBaz,
(Foo)int.MaxValue
};
string json1 = JsonConvert.SerializeObject(lfoo, Formatting.Indented, new StringEnumConverter { CamelCaseText = true });
Assert.AreEqual(@"[
""Bat, baz"",
""foo_bar"",
""Bat"",
""baz"",
""foo_bar, baz"",
2147483647
]", json1);
IList<Foo> foos = JsonConvert.DeserializeObject<List<Foo>>(json1);
Assert.AreEqual(6, foos.Count);
Assert.AreEqual(Foo.Bat | Foo.SerializeAsBaz, foos[0]);
Assert.AreEqual(Foo.FooBar, foos[1]);
Assert.AreEqual(Foo.Bat, foos[2]);
Assert.AreEqual(Foo.SerializeAsBaz, foos[3]);
Assert.AreEqual(Foo.FooBar | Foo.SerializeAsBaz, foos[4]);
Assert.AreEqual((Foo)int.MaxValue, foos[5]);
List<Bar> lbar = new List<Bar>() { Bar.FooBar, Bar.Bat, Bar.SerializeAsBaz };
string json2 = JsonConvert.SerializeObject(lbar, Formatting.Indented, new StringEnumConverter { CamelCaseText = true });
Assert.AreEqual(@"[
""foo_bar"",
""Bat"",
""baz""
]", json2);
IList<Bar> bars = JsonConvert.DeserializeObject<List<Bar>>(json2);
Assert.AreEqual(3, bars.Count);
Assert.AreEqual(Bar.FooBar, bars[0]);
Assert.AreEqual(Bar.Bat, bars[1]);
Assert.AreEqual(Bar.SerializeAsBaz, bars[2]);
}
// Define other methods and classes here
[Flags]
[JsonConverter(typeof(StringEnumConverter))]
private enum Foo
{
[EnumMember(Value = "foo_bar")]
FooBar = 0x01,
Bat = 0x02,
[EnumMember(Value = "baz")]
SerializeAsBaz = 0x4,
}
[JsonConverter(typeof(StringEnumConverter))]
private enum Bar
{
[EnumMember(Value = "foo_bar")]
FooBar,
Bat,
[EnumMember(Value = "baz")]
SerializeAsBaz
}
#endif
}
}

View File

@@ -0,0 +1,131 @@
#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
using System;
using Newtonsoft.Json.Converters;
#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
namespace Newtonsoft.Json.Tests.Converters
{
public class VersionClass
{
public VersionClass(string version1, string version2)
{
StringProperty1 = "StringProperty1";
Version1 = new Version(version1);
Version2 = new Version(version2);
StringProperty2 = "StringProperty2";
}
public VersionClass()
{
}
public string StringProperty1 { get; set; }
public Version Version1 { get; set; }
public Version Version2 { get; set; }
public string StringProperty2 { get; set; }
}
[TestFixture]
public class VersionConverterTests : TestFixtureBase
{
private void SerializeVersionClass(string version1, string version2)
{
VersionClass versionClass = new VersionClass(version1, version2);
string json = JsonConvert.SerializeObject(versionClass, Formatting.Indented, new VersionConverter());
string expectedJson = string.Format(@"{{
""StringProperty1"": ""StringProperty1"",
""Version1"": ""{0}"",
""Version2"": ""{1}"",
""StringProperty2"": ""StringProperty2""
}}", version1, version2);
Assert.AreEqual(expectedJson, json);
}
[Test]
public void SerializeVersionClass()
{
SerializeVersionClass("1.0.0.0", "2.0.0.0");
SerializeVersionClass("1.2.0.0", "2.3.0.0");
SerializeVersionClass("1.2.3.0", "2.3.4.0");
SerializeVersionClass("1.2.3.4", "2.3.4.5");
SerializeVersionClass("1.2", "2.3");
SerializeVersionClass("1.2.3", "2.3.4");
SerializeVersionClass("1.2.3.4", "2.3.4.5");
}
private void DeserializeVersionClass(string version1, string version2)
{
string json = string.Format(@"{{""StringProperty1"": ""StringProperty1"", ""Version1"": ""{0}"", ""Version2"": ""{1}"", ""StringProperty2"": ""StringProperty2""}}", version1, version2);
Version expectedVersion1 = new Version(version1);
Version expectedVersion2 = new Version(version2);
VersionClass versionClass = JsonConvert.DeserializeObject<VersionClass>(json, new VersionConverter());
Assert.AreEqual("StringProperty1", versionClass.StringProperty1);
Assert.AreEqual(expectedVersion1, versionClass.Version1);
Assert.AreEqual(expectedVersion2, versionClass.Version2);
Assert.AreEqual("StringProperty2", versionClass.StringProperty2);
}
[Test]
public void DeserializeVersionClass()
{
DeserializeVersionClass("1.0.0.0", "2.0.0.0");
DeserializeVersionClass("1.2.0.0", "2.3.0.0");
DeserializeVersionClass("1.2.3.0", "2.3.4.0");
DeserializeVersionClass("1.2.3.4", "2.3.4.5");
DeserializeVersionClass("1.2", "2.3");
DeserializeVersionClass("1.2.3", "2.3.4");
DeserializeVersionClass("1.2.3.4", "2.3.4.5");
}
[Test]
public void RoundtripImplicitConverter()
{
var version = new Version(1, 0, 0, 0);
string reportJSON = JsonConvert.SerializeObject(version);
//Test
Version report2 = JsonConvert.DeserializeObject<Version>(reportJSON);
string reportJSON2 = JsonConvert.SerializeObject(report2);
Assert.AreEqual(reportJSON, reportJSON2);
}
}
}

View File

@@ -0,0 +1,177 @@
#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.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
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.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Tests.Documentation
{
public class Employee
{
public string Name { get; set; }
public Employee Manager { get; set; }
}
#region ShouldSerializeContractResolver
public class ShouldSerializeContractResolver : DefaultContractResolver
{
public new static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (property.DeclaringType == typeof(Employee) && property.PropertyName == "Manager")
{
property.ShouldSerialize =
instance =>
{
Employee e = (Employee)instance;
return e.Manager != e;
};
}
return property;
}
}
#endregion
[TestFixture]
public class ConditionalPropertiesTests : TestFixtureBase
{
#region EmployeeShouldSerializeExample
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);
}
}
#endregion
[Test]
public void ShouldSerializeClassTest()
{
#region ShouldSerializeClassTest
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"
// }
// ]
#endregion
Assert.AreEqual(@"[
{
""Name"": ""Joe Employee"",
""Manager"": {
""Name"": ""Mike Manager""
}
},
{
""Name"": ""Mike Manager""
}
]", json);
}
[Test]
public void ShouldSerializeContractResolverTest()
{
Newtonsoft.Json.Tests.Documentation.Employee joe = new Newtonsoft.Json.Tests.Documentation.Employee();
joe.Name = "Joe Employee";
Newtonsoft.Json.Tests.Documentation.Employee mike = new Newtonsoft.Json.Tests.Documentation.Employee();
mike.Name = "Mike Manager";
joe.Manager = mike;
mike.Manager = mike;
string json = JsonConvert.SerializeObject(
new[] { joe, mike },
Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = ShouldSerializeContractResolver.Instance
});
Assert.AreEqual(@"[
{
""Name"": ""Joe Employee"",
""Manager"": {
""Name"": ""Mike Manager""
}
},
{
""Name"": ""Mike Manager""
}
]", json);
}
}
}
#endif

View File

@@ -0,0 +1,182 @@
#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 System.Xml;
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.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
namespace Newtonsoft.Json.Tests.Documentation
{
public class ConvertingJsonAndXmlTests
{
public void SerializeXmlNode()
{
#region SerializeXmlNode
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 jsonText = JsonConvert.SerializeXmlNode(doc);
//{
// "?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"
// }
// ]
// }
//}
#endregion
}
public void DeserializeXmlNode()
{
#region DeserializeXmlNode
string 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'
}
]
}
}";
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
// <?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>
#endregion
}
public void ForceJsonArray()
{
#region ForceJsonArray
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);
//{
// "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);
//{
// "person": {
// "@id": "1",
// "name": "Alan",
// "url": "http://www.google.com",
// "role": [
// "Admin"
// ]
// }
//}
#endregion
}
}
}
#endif

View File

@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation
{
public class JsonNetVsWindowsDataJsonTests
{
public void CreatingJson()
{
#if NETFX_CORE
#region CreatingJSON
// Windows.Data.Json
// -----------------
JsonObject jsonObject = new JsonObject
{
{"CPU", JsonValue.CreateStringValue("Intel")},
{
"Drives", new JsonArray
{
JsonValue.CreateStringValue("DVD read/writer"),
JsonValue.CreateStringValue("500 gigabyte hard drive")
}
}
};
string json1 = jsonObject.Stringify();
// LINQ to JSON
// ------------
JObject jObject = new JObject
{
{"CPU", "Intel"},
{
"Drives", new JArray
{
"DVD read/writer",
"500 gigabyte hard drive"
}
}
};
string json2 = jObject.ToString();
#endregion
#endif
}
public void QueryingJson()
{
#if NETFX_CORE
#region QueryingJSON
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'
]
}
]
}
}";
// Windows.Data.Json
// -----------------
JsonObject jsonObject = JsonObject.Parse(json);
string itemTitle1 = jsonObject["channel"].GetObject()["item"].GetArray()[0].GetObject()["title"].GetString();
// LINQ to JSON
// ------------
JObject jObject = JObject.Parse(json);
string itemTitle2 = (string)jObject["channel"]["item"][0]["title"];
#endregion
#endif
}
public void Converting()
{
#if NETFX_CORE
#region Converting
JsonObject jsonObject = new JsonObject
{
{"CPU", JsonValue.CreateStringValue("Intel")},
{"Drives", new JsonArray {
JsonValue.CreateStringValue("DVD read/writer"),
JsonValue.CreateStringValue("500 gigabyte hard drive")
}
}
};
// convert Windows.Data.Json to LINQ to JSON
JObject o = JObject.FromObject(jsonObject);
// convert LINQ to JSON to Windows.Data.Json
JArray a = (JArray)o["Drives"];
JsonArray jsonArray = a.ToObject<JsonArray>();
#endregion
#endif
}
}
}

View File

@@ -0,0 +1,185 @@
#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

View File

@@ -0,0 +1,462 @@
#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.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 static class File
{
public static StreamReader OpenText(string path)
{
return null;
}
public static StreamWriter CreateText(string path)
{
return null;
}
public static void WriteAllText(string path, string contents)
{
Console.WriteLine(contents);
}
public static string ReadAllText(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
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",
// "2000-05-23T00:00:00"
// ]
#endregion
}
public class Post
{
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public IList<string> Categories { get; set; }
}
private List<Post> GetPosts()
{
return null;
}
public void LinqToJsonCreateDeclaratively()
{
#region LinqToJsonCreateDeclaratively
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 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
}
public void LinqToJsonCreateFromObject()
{
List<Post> posts = null;
#region LinqToJsonCreateFromObject
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
}
}
});
#endregion
}
public void LinqToJsonCreateParse()
{
#region LinqToJsonCreateParse
string json = @"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
#endregion
}
public void LinqToJsonCreateParseArray()
{
#region LinqToJsonCreateParseArray
string json = @"[
'Small',
'Medium',
'Large'
]";
JArray a = JArray.Parse(json);
#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 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();
#region LinqToJsonQuerying
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
}
#region LinqToJsonDeserializeObject
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; }
}
#endregion
public void LinqToJsonDeserializeExample()
{
#region LinqToJsonDeserializeExample
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
#endregion
}
public void SelectTokenSimple()
{
JObject o = new JObject();
#region SelectTokenSimple
string name = (string)o.SelectToken("Manufacturers[0].Name");
#endregion
}
public void SelectTokenComplex()
{
#region SelectTokenComplex
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");
// Acme Co
decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
// 50
string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
// Elbow Grease
#endregion
}
public void SelectTokenLinq()
{
JObject o = new JObject();
#region SelectTokenLinq
IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
// Lambton Quay
// Willis Street
IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList();
// null
// Headlight Fluid
decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
// 149.95
#endregion
}
}
}
#endif

View File

@@ -0,0 +1,222 @@
#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.Net;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
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.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Tests.Documentation
{
public class HttpClient
{
public Task<string> GetStringAsync(string requestUri)
{
return null;
}
public Task<Stream> GetStreamAsync(string requestUri)
{
return null;
}
}
#region JsonConverterAttribute
[JsonConverter(typeof(PersonConverter))]
public class Person
{
public Person()
{
Likes = new List<string>();
}
public string Name { get; set; }
public IList<string> Likes { get; private set; }
}
#endregion
#region JsonConverterContractResolver
public class ConverterContractResolver : DefaultContractResolver
{
public new static readonly ConverterContractResolver Instance = new ConverterContractResolver();
protected override JsonContract CreateContract(Type objectType)
{
JsonContract contract = base.CreateContract(objectType);
// this will only be called once and then cached
if (objectType == typeof(DateTime) || objectType == typeof(DateTimeOffset))
contract.Converter = new JavaScriptDateTimeConverter();
return contract;
}
}
#endregion
public class PersonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return null;
}
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Person));
}
}
[TestFixture]
public class PerformanceTests : TestFixtureBase
{
[Test]
public void ConverterContractResolverTest()
{
string json = JsonConvert.SerializeObject(new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc), new JsonSerializerSettings
{
ContractResolver = ConverterContractResolver.Instance
});
Console.WriteLine(json);
}
public void DeserializeString()
{
#region DeserializeString
HttpClient client = new HttpClient();
// read the json into a string
// string could potentially be very large and cause memory problems
string json = client.GetStringAsync("http://www.test.com/large.json").Result;
Person p = JsonConvert.DeserializeObject<Person>(json);
#endregion
}
public void DeserializeStream()
{
#region DeserializeStream
HttpClient client = new HttpClient();
using (Stream s = client.GetStreamAsync("http://www.test.com/large.json").Result)
using (StreamReader sr = new StreamReader(s))
using (JsonReader reader = new JsonTextReader(sr))
{
JsonSerializer serializer = new JsonSerializer();
// read the json from a stream
// json size doesn't matter because only a small piece is read at a time from the HTTP request
Person p = serializer.Deserialize<Person>(reader);
}
#endregion
}
}
public static class PersonWriter
{
#region ReaderWriter
public static string ToJson(this Person p)
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
// {
writer.WriteStartObject();
// "name" : "Jerry"
writer.WritePropertyName("name");
writer.WriteValue(p.Name);
// "likes": ["Comedy", "Superman"]
writer.WritePropertyName("likes");
writer.WriteStartArray();
foreach (string like in p.Likes)
{
writer.WriteValue(like);
}
writer.WriteEndArray();
// }
writer.WriteEndObject();
return sw.ToString();
}
#endregion
public static Person ToPerson(this string s)
{
StringReader sr = new StringReader(s);
JsonTextReader reader = new JsonTextReader(sr);
Person p = new Person();
// {
reader.Read();
// "name"
reader.Read();
// "Jerry"
p.Name = reader.ReadAsString();
// "likes"
reader.Read();
// [
reader.Read();
// "Comedy", "Superman", ]
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
p.Likes.Add((string)reader.Value);
}
// }
reader.Read();
return p;
}
}
}
#endif

View File

@@ -0,0 +1,151 @@
#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.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
namespace Newtonsoft.Json.Tests.Documentation
{
[TestFixture]
public class ReadingAndWritingJsonTests : TestFixtureBase
{
public void ReadingAndWritingJsonText()
{
#region ReadingAndWritingJsonText
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();
}
// {
// "CPU": "Intel",
// "PSU": "500W",
// "Drives": [
// "DVD read/writer"
// /*(broken)*/,
// "500 gigabyte hard drive",
// "200 gigabype hard drive"
// ]
// }
#endregion
}
[Test]
public void ReadingJsonText()
{
#region ReadingJsonText
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
#endregion
}
public void ReadingAndWritingJsonLinq()
{
#region ReadingAndWritingJsonLinq
JObject o = new JObject(
new JProperty("Name", "John Smith"),
new JProperty("BirthDate", new DateTime(1983, 3, 20))
);
JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));
Console.WriteLine(p.Name);
// John Smith
#endregion
}
}
}
#endif

View File

@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Bson;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Bson
{
public class DeserializeFromBson
{
#region Types
public class Event
{
public string Name { get; set; }
public DateTime StartDate { get; set; }
}
#endregion
public void Example()
{
#region Usage
byte[] data = Convert.FromBase64String("MQAAAAJOYW1lAA8AAABNb3ZpZSBQcmVtaWVyZQAJU3RhcnREYXRlAMDgKWE8AQAAAA==");
MemoryStream ms = new MemoryStream(data);
using (BsonReader reader = new BsonReader(ms))
{
JsonSerializer serializer = new JsonSerializer();
Event e = serializer.Deserialize<Event>(reader);
Console.WriteLine(e.Name);
// Movie Premiere
}
#endregion
}
}
}

View File

@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Bson;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Bson
{
public class DeserializeFromBsonCollection
{
#region Types
public class Event
{
public string Name { get; set; }
public DateTime StartDate { get; set; }
}
#endregion
public void Example()
{
//IList<Event> e = new List<Event>
// {
// new Event {StartDate = new DateTime(2013, 3, 31), Name = "Easter"}
// };
//MemoryStream ms1 = new MemoryStream();
//using (BsonWriter writer = new BsonWriter(ms1))
//{
// JsonSerializer serializer = new JsonSerializer();
// serializer.Serialize(writer, e);
//}
//string ss = Convert.ToBase64String(ms1.ToArray());
//Console.WriteLine(ss);
#region Usage
string s = "MQAAAAMwACkAAAACTmFtZQAHAAAARWFzdGVyAAlTdGFydERhdGUAgDf0uj0BAAAAAA==";
byte[] data = Convert.FromBase64String(s);
MemoryStream ms = new MemoryStream(data);
using (BsonReader reader = new BsonReader(ms))
{
reader.ReadRootValueAsArray = true;
JsonSerializer serializer = new JsonSerializer();
IList<Event> events = serializer.Deserialize<IList<Event>>(reader);
Console.WriteLine(events.Count);
// 1
Console.WriteLine(events[0].Name);
// Easter
}
#endregion
}
}
}

View File

@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Bson
{
public class SerializeToBson
{
#region Types
public class Event
{
public string Name { get; set; }
public DateTime StartDate { get; set; }
}
#endregion
public void Example()
{
#region Usage
Event e = new Event
{
Name = "Movie Premiere",
StartDate = new DateTime(2013, 1, 22, 20, 30, 0)
};
MemoryStream ms = new MemoryStream();
using (BsonWriter writer = new BsonWriter(ms))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, e);
}
string data = Convert.ToBase64String(ms.ToArray());
Console.WriteLine(data);
// MQAAAAJOYW1lAA8AAABNb3ZpZSBQcmVtaWVyZQAJU3RhcnREYXRlAMDgKWE8AQAAAA==
#endregion
}
}
}

View File

@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Json
{
public class ReadJsonWithJsonTextReader
{
public void Example()
{
#region Usage
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
#endregion
}
}
}

View File

@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Json
{
public class WriteJsonWithJsonTextWriter
{
public void Example()
{
#region Usage
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"
// ]
// }
#endregion
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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 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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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 CreateJsonManually
{
public void Example()
{
#region Usage
JArray array = new JArray();
array.Add("Manual text");
array.Add(new DateTime(2000, 5, 23));
JObject o = new JObject();
o["MyArray"] = array;
string json = o.ToString();
// {
// "MyArray": [
// "Manual text",
// "2000-05-23T00:00:00"
// ]
// }
#endregion
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -0,0 +1,72 @@
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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -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
}
}
}

View File

@@ -0,0 +1,59 @@
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.Samples.Schema
{
public class CreateJsonSchemaManually
{
public void Example()
{
#region Usage
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
#endregion
}
}
}

View File

@@ -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.Samples.Schema
{
public class JTokenIsValid
{
public void Example()
{
#region Usage
JsonSchema schema = JsonSchema.Parse(@"{
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {
'type': 'array',
'items': {'type':'string'}
}
}
}");
JObject person = JObject.Parse(@"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");
IList<string> errorMessages;
bool valid = person.IsValid(schema, out errorMessages);
Console.WriteLine(valid);
// true
#endregion
}
}
}

View File

@@ -0,0 +1,49 @@
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.Samples.Schema
{
public class JTokenIsValidWithMessages
{
public void Example()
{
#region Usage
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.
#endregion
}
}
}

View File

@@ -0,0 +1,48 @@
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.Samples.Schema
{
public class JTokenValidateWithEvent
{
public void Example()
{
#region Usage
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.
#endregion
}
}
}

View File

@@ -0,0 +1,41 @@
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.Samples.Schema
{
public class JsonSchemaParse
{
public void Example()
{
#region Usage
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
#endregion
}
}
}

View File

@@ -0,0 +1,61 @@
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema
{
public class JsonValidatingReaderAndSerializer
{
#region Types
public class Person
{
public string Name { get; set; }
public IList<string> Hobbies { get; set; }
}
#endregion
public void Example()
{
#region Usage
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
#endregion
}
}
}

View File

@@ -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.Samples.Schema
{
public class LoadJsonSchemaFromFile
{
public void Example()
{
#region Usage
// 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);
}
#endregion
}
}
}

View File

@@ -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.Samples.Schema
{
public class RefJsonSchemaResolver
{
public void Example()
{
#region Usage
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
#endregion
}
}
}

View File

@@ -0,0 +1,32 @@
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema
{
public class SaveJsonSchemaToFile
{
public void Example()
{
#region Usage
JsonSchema schema = new JsonSchema
{
Type = JsonSchemaType.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);
}
#endregion
}
}
}

View File

@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class CustomContractResolver
{
#region Types
public class DynamicContractResolver : DefaultContractResolver
{
private readonly char _startingWithChar;
public DynamicContractResolver(char startingWithChar)
{
_startingWithChar = startingWithChar;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
// only serializer properties that start with the specified character
properties =
properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();
return properties;
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get { return FirstName + " " + LastName; }
}
}
#endregion
public void Example()
{
#region Usage
Person person = new Person
{
FirstName = "Dennis",
LastName = "Deepwater-Diver"
};
string startingWithF = JsonConvert.SerializeObject(person, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('F') });
Console.WriteLine(startingWithF);
// {
// "FirstName": "Dennis",
// "FullName": "Dennis Deepwater-Diver"
// }
string startingWithL = JsonConvert.SerializeObject(person, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('L') });
Console.WriteLine(startingWithL);
// {
// "LastName": "Deepwater-Diver"
// }
#endregion
}
}
}

View File

@@ -0,0 +1,100 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class CustomJsonConverter
{
#region Types
public class KeysJsonConverter : JsonConverter
{
private readonly 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("Unnecessary because CanRead is false. The type will skip the converter.");
}
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; }
}
#endregion
public void Example()
{
#region Usage
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
#endregion
}
}
}

View File

@@ -0,0 +1,81 @@
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class CustomTraceWriter
{
#region Types
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;
}
}
}
#endregion
public void Example()
{
#region Usage
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"
// ]
#endregion
}
}
}

View File

@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class DataContractAndDataMember
{
#region Types
[DataContract]
public class File
{
// excluded from serialization
// does not have DataMemberAttribute
public Guid Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Size { get; set; }
}
#endregion
public void Example()
{
#region Usage
File file = new File
{
Id = Guid.NewGuid(),
Name = "ImportantLegalDocuments.docx",
Size = 50 * 1024
};
string json = JsonConvert.SerializeObject(file, Formatting.Indented);
Console.WriteLine(json);
// {
// "Name": "ImportantLegalDocuments.docx",
// "Size": 51200
// }
#endregion
}
}
}

View File

@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class DefaultValueAttributeIgnore
{
#region Types
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
[DefaultValue(" ")]
public string FullName
{
get { return FirstName + " " + LastName; }
}
}
#endregion
public void Example()
{
#region Usage
Customer customer = new Customer();
string jsonIncludeDefaultValues = JsonConvert.SerializeObject(customer, Formatting.Indented);
Console.WriteLine(jsonIncludeDefaultValues);
// {
// "FirstName": null,
// "LastName": null,
// "FullName": " "
// }
string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(customer, Formatting.Indented, new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Ignore
});
Console.WriteLine(jsonIgnoreDefaultValues);
// {}
#endregion
}
}
}

View File

@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class DefaultValueHandlingIgnore
{
#region Types
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person Partner { get; set; }
public decimal? Salary { get; set; }
}
#endregion
public void Example()
{
#region Usage
Person person = new Person();
string jsonIncludeDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented);
Console.WriteLine(jsonIncludeDefaultValues);
// {
// "Name": null,
// "Age": 0,
// "Partner": null,
// "Salary": null
// }
string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Ignore
});
Console.WriteLine(jsonIgnoreDefaultValues);
// {}
#endregion
}
}
}

View File

@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class DeserializeAnonymousType
{
public void Example()
{
#region Usage
var definition = new { Name = "" };
string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);
Console.WriteLine(customer1.Name);
// James
string json2 = @"{'Name':'Mike'}";
var customer2 = JsonConvert.DeserializeAnonymousType(json2, definition);
Console.WriteLine(customer2.Name);
// Mike
#endregion
}
}
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class DeserializeCollection
{
public void Example()
{
#region Usage
string json = @"['Starcraft','Halo','Legend of Zelda']";
List<string> videogames = JsonConvert.DeserializeObject<List<string>>(json);
Console.WriteLine(string.Join(", ", videogames));
// Starcraft, Halo, Legend of Zelda
#endregion
}
}
}

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class DeserializeConstructorHandling
{
#region Types
public class Website
{
public string Url { get; set; }
private Website()
{
}
public Website(Website website)
{
if (website == null)
throw new ArgumentNullException("website");
Url = website.Url;
}
}
#endregion
public void Example()
{
#region Usage
string json = @"{'Url':'http://www.google.com'}";
try
{
JsonConvert.DeserializeObject<Website>(json);
}
catch (TargetInvocationException ex)
{
Console.WriteLine(ex);
// Value cannot be null.
// Parameter name: website
}
Website website = JsonConvert.DeserializeObject<Website>(json, new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
});
Console.WriteLine(website.Url);
// http://www.google.com
#endregion
}
}
}

View File

@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class DeserializeCustomCreationConverter
{
#region Types
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
}
public class Employee : Person
{
public string Department { get; set; }
public string JobTitle { get; set; }
}
public class PersonConverter : CustomCreationConverter<Person>
{
public override Person Create(Type objectType)
{
return new Employee();
}
}
#endregion
public void Example()
{
#region Usage
string json = @"{
'Department': 'Furniture',
'JobTitle': 'Carpenter',
'FirstName': 'John',
'LastName': 'Joinery',
'BirthDate': '1983-02-02T00:00:00'
}";
Person person = JsonConvert.DeserializeObject<Person>(json, new PersonConverter());
Console.WriteLine(person.GetType().Name);
// Employee
Employee employee = (Employee)person;
Console.WriteLine(employee.JobTitle);
// Capenter
#endregion
}
}
}

View File

@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class DeserializeDataSet
{
public void Example()
{
#region Usage
string json = @"{
'Table1': [
{
'id': 0,
'item': 'item 0'
},
{
'id': 1,
'item': 'item 1'
}
]
}";
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);
DataTable dataTable = dataSet.Tables["Table1"];
Console.WriteLine(dataTable.Rows.Count);
// 2
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(row["id"] + " - " + row["item"]);
}
// 0 - item 0
// 1 - item 1
#endregion
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class DeserializeDictionary
{
public void Example()
{
#region Usage
string json = @"{
'href': '/account/login.aspx',
'target': '_blank'
}";
Dictionary<string, string> htmlAttributes = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
Console.WriteLine(htmlAttributes["href"]);
// /account/login.aspx
Console.WriteLine(htmlAttributes["target"]);
// _blank
#endregion
}
}
}

View File

@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class DeserializeMissingMemberHandling
{
#region Types
public class Account
{
public string FullName { get; set; }
public bool Deleted { get; set; }
}
#endregion
public void Example()
{
#region Usage
string json = @"{
'FullName': 'Dan Deleted',
'Deleted': true,
'DeletedDate': '2013-01-20T00:00:00'
}";
try
{
JsonConvert.DeserializeObject<Account>(json, new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Error
});
}
catch (JsonSerializationException ex)
{
Console.WriteLine(ex.Message);
// Could not find member 'DeletedDate' on object of type 'Account'. Path 'DeletedDate', line 4, position 23.
}
#endregion
}
}
}

View File

@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class DeserializeObject
{
#region Types
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
#endregion
public void Example()
{
#region Usage
string json = @"{
'Email': 'james@example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
// james@example.com
#endregion
}
}
}

View File

@@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class DeserializeObjectCreationHandling
{
#region Types
public class UserViewModel
{
public string Name { get; set; }
public IList<string> Offices { get; private set; }
public UserViewModel()
{
Offices = new List<string>
{
"Auckland",
"Wellington",
"Christchurch"
};
}
}
#endregion
public void Example()
{
#region Usage
string json = @"{
'Name': 'James',
'Offices': [
'Auckland',
'Wellington',
'Christchurch'
]
}";
UserViewModel model1 = JsonConvert.DeserializeObject<UserViewModel>(json);
foreach (string office in model1.Offices)
{
Console.WriteLine(office);
}
// Auckland
// Wellington
// Christchurch
// Auckland
// Wellington
// Christchurch
UserViewModel model2 = JsonConvert.DeserializeObject<UserViewModel>(json, new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace
});
foreach (string office in model2.Offices)
{
Console.WriteLine(office);
}
// Auckland
// Wellington
// Christchurch
#endregion
}
}
}

View File

@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using File = System.IO.File;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class DeserializeWithJsonSerializerFromFile
{
#region Types
public class Movie
{
public string Name { get; set; }
public int Year { get; set; }
}
#endregion
public void Example()
{
#region Usage
// read file into a string and deserialize JSON to a type
Movie movie1 = JsonConvert.DeserializeObject<Movie>(File.ReadAllText(@"c:\movie.json"));
// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\movie.json"))
{
JsonSerializer serializer = new JsonSerializer();
Movie movie2 = (Movie)serializer.Deserialize(file, typeof(Movie));
}
#endregion
}
}
}

View File

@@ -0,0 +1,64 @@
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.Samples.Serializer
{
public class ErrorHandlingAttribute
{
#region Types
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;
}
}
#endregion
public void Example()
{
#region Usage
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"
// }
#endregion
}
}
}

View File

@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class ErrorHandlingEvent
{
public void Example()
{
#region Usage
List<string> errors = new List<string>();
List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(@"[
'2009-09-09T00:00:00Z',
'I am not a date and will error!',
[
1
],
'1977-02-20T00:00:00Z',
null,
'2000-12-01T00:00:00Z'
]",
new JsonSerializerSettings
{
Error = delegate(object sender, ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
},
Converters = { new IsoDateTimeConverter() }
});
// 2009-09-09T00:00:00Z
// 1977-02-20T00:00:00Z
// 2000-12-01T00:00:00Z
// The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.
// Unexpected token parsing date. Expected String, got StartArray.
// Cannot convert null value to System.DateTime.
#endregion
}
}
}

View File

@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class JsonConverterAttributeClass
{
#region Types
public class UserConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
User user = (User)value;
writer.WriteValue(user.UserName);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
User user = new User();
user.UserName = (string)reader.Value;
return user;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(User);
}
}
[JsonConverter(typeof(UserConverter))]
public class User
{
public string UserName { get; set; }
}
#endregion
public void Example()
{
#region Usage
User user = new User
{
UserName = @"domain\username"
};
string json = JsonConvert.SerializeObject(user, Formatting.Indented);
Console.WriteLine(json);
// "domain\\username"
#endregion
}
}
}

View File

@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class JsonConverterAttributeProperty
{
#region Types
public enum UserStatus
{
NotConfirmed,
Active,
Deleted
}
public class User
{
public string UserName { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public UserStatus Status { get; set; }
}
#endregion
public void Example()
{
#region Usage
User user = new User
{
UserName = @"domain\username",
Status = UserStatus.Deleted
};
string json = JsonConvert.SerializeObject(user, Formatting.Indented);
Console.WriteLine(json);
// {
// "UserName": "domain\\username",
// "Status": "Deleted"
// }
#endregion
}
}
}

View File

@@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class JsonObjectAttributeOptIn
{
#region Types
[JsonObject(MemberSerialization.OptIn)]
public class File
{
// excluded from serialization
// does not have JsonPropertyAttribute
public Guid Id { get; set; }
[JsonProperty]
public string Name { get; set; }
[JsonProperty]
public int Size { get; set; }
}
#endregion
public void Example()
{
#region Usage
File file = new File
{
Id = Guid.NewGuid(),
Name = "ImportantLegalDocuments.docx",
Size = 50 * 1024
};
string json = JsonConvert.SerializeObject(file, Formatting.Indented);
Console.WriteLine(json);
// {
// "Name": "ImportantLegalDocuments.docx",
// "Size": 51200
// }
#endregion
}
}
}

View File

@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class JsonObjectAttributeOverrideIEnumerable
{
#region Types
[JsonObject]
public class Directory : IEnumerable<string>
{
public string Name { get; set; }
public IList<string> Files { get; set; }
public Directory()
{
Files = new List<string>();
}
public IEnumerator<string> GetEnumerator()
{
return Files.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
#endregion
public void Example()
{
#region Usage
Directory directory = new Directory
{
Name = "My Documents",
Files =
{
"ImportantLegalDocuments.docx",
"WiseFinancalAdvice.xlsx"
}
};
string json = JsonConvert.SerializeObject(directory, Formatting.Indented);
Console.WriteLine(json);
// {
// "Name": "My Documents",
// "Files": [
// "ImportantLegalDocuments.docx",
// "WiseFinancalAdvice.xlsx"
// ]
// }
#endregion
}
}
}

View File

@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
public class JsonPropertyItemLevelSetting
{
#region Types
public class Business
{
public string Name { get; set; }
[JsonProperty(ItemIsReference = true)]
public IList<Employee> Employees { get; set; }
}
public class Employee
{
public string Name { get; set; }
[JsonProperty(IsReference = true)]
public Employee Manager { get; set; }
}
#endregion
public void Example()
{
#region Usage
Employee manager = new Employee
{
Name = "George-Michael"
};
Employee worker = new Employee
{
Name = "Maeby",
Manager = manager
};
Business business = new Business
{
Name = "Acme Ltd.",
Employees = new List<Employee>
{
manager,
worker
}
};
string json = JsonConvert.SerializeObject(business, Formatting.Indented);
Console.WriteLine(json);
// {
// "Name": "Acme Ltd.",
// "Employees": [
// {
// "$id": "1",
// "Name": "George-Michael",
// "Manager": null
// },
// {
// "$id": "2",
// "Name": "Maeby",
// "Manager": {
// "$ref": "1"
// }
// }
// ]
// }
#endregion
}
}
}

Some files were not shown because too many files have changed in this diff Show More