-Added reading and writing binary JSON (BSON) support - work in progress

-Added BsonReader, BsonWriter
-Added support for reading and writing byte arrays to JsonReader, JsonWriter and LINQ to JSON classes
-Added ReadAsBytes to JsonReader
-Changed Silverlight build serializer to look for a TypeConverter
-Changed .NET build to not rely on System.ComponentModel.DataAnnotations assembly to support .NET 4.0 client profile
-Remove DateTimeOffset stand-in from Compact Framework build
-Fixed .NET 2.0 build to run on environments without .NET 2.0 SP1
-Fixed deserialization to always use a new value created from a JsonConverter
-Fixed XmlNodeConverter to support converting comments in JSON
This commit is contained in:
JamesNK
2009-12-06 23:10:14 +00:00
parent 7d845d1f13
commit f1a9993723
59 changed files with 1952 additions and 697 deletions
@@ -0,0 +1,180 @@
#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.Linq;
using System.Text;
using NUnit.Framework;
using Newtonsoft.Json.Bson;
using System.IO;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Bson
{
public class BsonReaderTests : TestFixtureBase
{
[Test]
public void ReadSingleObject()
{
byte[] data = MiscellaneousUtils.HexToBytes("0F-00-00-00-10-42-6C-61-68-00-01-00-00-00-00");
MemoryStream ms = new MemoryStream(data);
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.AreEqual("Blah", reader.Value);
Assert.AreEqual(typeof(string), reader.ValueType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.Integer, reader.TokenType);
Assert.AreEqual(1, reader.Value);
Assert.AreEqual(typeof(long), reader.ValueType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
Assert.IsFalse(reader.Read());
}
[Test]
public void ReadObjectBsonFromSite()
{
byte[] data = MiscellaneousUtils.HexToBytes("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");
MemoryStream ms = new MemoryStream(data);
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.AreEqual("0", reader.Value);
Assert.AreEqual(typeof(string), reader.ValueType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.AreEqual("a", reader.Value);
Assert.AreEqual(typeof(string), reader.ValueType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.AreEqual("1", reader.Value);
Assert.AreEqual(typeof(string), reader.ValueType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.AreEqual("b", reader.Value);
Assert.AreEqual(typeof(string), reader.ValueType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.AreEqual("2", reader.Value);
Assert.AreEqual(typeof(string), reader.ValueType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.AreEqual("c", reader.Value);
Assert.AreEqual(typeof(string), reader.ValueType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
Assert.IsFalse(reader.Read());
}
[Test]
public void ReadArrayBsonFromSite()
{
byte[] data = MiscellaneousUtils.HexToBytes("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");
MemoryStream ms = new MemoryStream(data);
BsonReader reader = new BsonReader(ms, true);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartArray, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.AreEqual("a", reader.Value);
Assert.AreEqual(typeof(string), reader.ValueType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.AreEqual("b", reader.Value);
Assert.AreEqual(typeof(string), reader.ValueType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.AreEqual("c", reader.Value);
Assert.AreEqual(typeof(string), reader.ValueType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndArray, reader.TokenType);
Assert.IsFalse(reader.Read());
}
[Test]
public void ReadBytes()
{
byte[] data = MiscellaneousUtils.HexToBytes("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-02-48-65-6C-6C-6F-20-77-6F-72-6C-64-21-00");
MemoryStream ms = new MemoryStream(data);
BsonReader reader = new BsonReader(ms, true);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartArray, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.AreEqual("a", reader.Value);
Assert.AreEqual(typeof(string), reader.ValueType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.AreEqual("b", reader.Value);
Assert.AreEqual(typeof(string), reader.ValueType);
byte[] encodedStringData = reader.ReadAsBytes();
Assert.IsNotNull(encodedStringData);
Assert.AreEqual(JsonToken.Bytes, reader.TokenType);
Assert.AreEqual(encodedStringData, reader.Value);
Assert.AreEqual(typeof(byte[]), reader.ValueType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndArray, reader.TokenType);
Assert.IsFalse(reader.Read());
string decodedString = Encoding.UTF8.GetString(encodedStringData);
Assert.AreEqual("Hello world!", decodedString);
}
}
}
@@ -0,0 +1,112 @@
#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.Linq;
using System.Text;
using NUnit.Framework;
using Newtonsoft.Json.Bson;
using System.IO;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Bson
{
public class BsonWriterTests : TestFixtureBase
{
[Test]
public void WriteSingleObject()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartObject();
writer.WritePropertyName("Blah");
writer.WriteValue(1);
writer.WriteEndObject();
writer.Flush();
string bson = MiscellaneousUtils.BytesToHex(ms.ToArray());
Assert.AreEqual("0F-00-00-00-10-42-6C-61-68-00-01-00-00-00-00", bson);
}
[Test]
[ExpectedException(typeof(JsonWriterException), ExpectedMessage = "Cannot flush BsonWriter until JSON is complete.")]
public void FlushInsideObject()
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartObject();
writer.WritePropertyName("Blah");
writer.WriteValue(1);
writer.Flush();
}
[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 = MiscellaneousUtils.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-02-48-65-6C-6C-6F-20-77-6F-72-6C-64-21-00";
string bson = MiscellaneousUtils.BytesToHex(ms.ToArray());
Assert.AreEqual(expected, bson);
}
}
}
@@ -142,6 +142,7 @@ namespace Newtonsoft.Json.Tests.Converters
}
#endif
#if !PocketPC && !NET20
[Test]
public void SerializeDateTimeOffset()
{
@@ -266,6 +267,7 @@ namespace Newtonsoft.Json.Tests.Converters
string json2 = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
Assert.AreNotEqual(json, json2);
}
#endif
[Test]
public void BlogCodeSample()
@@ -47,6 +47,7 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual("new Date(976918263055)", result);
}
#if !PocketPC && !NET20
[Test]
public void SerializeDateTimeOffset()
{
@@ -85,15 +86,6 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual(@"{""PreField"":null,""DateTimeField"":new Date(976918263055),""DateTimeOffsetField"":new Date(976918263055),""PostField"":null}", result);
}
[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]
[ExpectedException(typeof(Exception), ExpectedMessage = "Cannot convert null value to System.DateTime.")]
public void DeserializeNullToNonNullable()
@@ -113,5 +105,15 @@ namespace Newtonsoft.Json.Tests.Converters
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);
}
}
}
@@ -523,6 +523,35 @@ namespace Newtonsoft.Json.Tests.Converters
string json = JsonConvert.SerializeXmlNode(doc);
Assert.AreEqual(@"{""name"":""O\""Connor""}", json);
}
[Test]
public void SerializeComment()
{
string xml = @"<span class=""vevent"">
<a class=""url"" href=""http://www.web2con.com/"">Text</a><!-- Hi! -->
</span>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeObject(doc, Formatting.Indented, new XmlNodeConverter());
string expected = @"{
""span"": {
""@class"": ""vevent"",
""a"": {
""@class"": ""url"",
""@href"": ""http://www.web2con.com/"",
""#text"": ""Text""
}/* Hi! */
}
}";
Assert.AreEqual(expected, jsonText);
XmlDocument newDoc = JsonConvert.DeserializeObject<XmlDocument>(jsonText, new XmlNodeConverter());
Assert.AreEqual(@"<span class=""vevent""><a class=""url"" href=""http://www.web2con.com/"">Text</a><!-- Hi! --></span>", newDoc.InnerXml);
}
}
}
#endif
+3 -1
View File
@@ -232,8 +232,10 @@ now brown cow?", '"', true);
value = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
Assert.AreEqual(@"""\/Date(0)\/""", JsonConvert.ToString(value));
#if !PocketPC && !NET20
value = new DateTimeOffset(JsonConvert.InitialJavaScriptDateTicks, TimeSpan.Zero);
Assert.AreEqual(@"""\/Date(0+0000)\/""", JsonConvert.ToString(value));
#endif
value = null;
Assert.AreEqual("null", JsonConvert.ToString(value));
@@ -271,7 +273,7 @@ now brown cow?", '"', true);
int i = JsonConvert.DeserializeObject<int>("1");
Assert.AreEqual(1, i);
#if !PocketPC
#if !PocketPC && !NET20
DateTimeOffset d = JsonConvert.DeserializeObject<DateTimeOffset>(@"""\/Date(-59011455539000+0000)\/""");
Assert.AreEqual(new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)), d);
#endif
@@ -469,5 +469,18 @@ namespace Newtonsoft.Json.Tests
reader.Read();
}
[Test]
public void ReadSingleBytes()
{
StringReader s = new StringReader(@"""SGVsbG8gd29ybGQu""");
JsonTextReader reader = new JsonTextReader(s);
byte[] data = reader.ReadAsBytes();
Assert.IsNotNull(data);
string text = Encoding.UTF8.GetString(data, 0, data.Length);
Assert.AreEqual("Hello world.", text);
}
}
}
@@ -103,13 +103,21 @@ namespace Newtonsoft.Json.Tests
jsonWriter.WriteValue((decimal?)1.1m);
jsonWriter.WriteValue((DateTime?)null);
jsonWriter.WriteValue((DateTime?)new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc));
#if !PocketPC && !NET20
jsonWriter.WriteValue((DateTimeOffset?)null);
jsonWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(JsonConvert.InitialJavaScriptDateTicks, TimeSpan.Zero));
#endif
jsonWriter.WriteEndArray();
}
string json = sw.ToString();
string expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""\/Date(0)\/"",null,""\/Date(0+0000)\/""]";
string expected;
#if !PocketPC && !NET20
expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""\/Date(0)\/"",null,""\/Date(0+0000)\/""]";
#else
expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""\/Date(0)\/""]";
#endif
Assert.AreEqual(expected, json);
}
@@ -532,5 +540,65 @@ _____'propertyName': NaN
Assert.AreEqual(expected, result);
}
[Test]
public void WriteSingleBytes()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
string text = "Hello world.";
byte[] data = Encoding.UTF8.GetBytes(text);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting);
jsonWriter.WriteValue(data);
}
string expected = @"""SGVsbG8gd29ybGQu""";
string result = sb.ToString();
Assert.AreEqual(expected, result);
byte[] d2 = Convert.FromBase64String(result.Trim('"'));
Assert.AreEqual(text, Encoding.UTF8.GetString(d2, 0, d2.Length));
}
[Test]
public void WriteBytesInArray()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
string text = "Hello world.";
byte[] data = Encoding.UTF8.GetBytes(text);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting);
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(data);
jsonWriter.WriteValue(data);
jsonWriter.WriteValue((object)data);
jsonWriter.WriteValue((byte[])null);
jsonWriter.WriteEndArray();
}
string expected = @"[
""SGVsbG8gd29ybGQu"",
""SGVsbG8gd29ybGQu"",
""SGVsbG8gd29ybGQu"",
null
]";
string result = sb.ToString();
Assert.AreEqual(expected, result);
}
}
}
@@ -11,8 +11,6 @@ using System.IO;
using System.Collections;
#if !PocketPC && !SILVERLIGHT
using System.Web.UI;
using System.Collections;
using System.ComponentModel;
#endif
namespace Newtonsoft.Json.Tests.Linq
@@ -596,7 +594,7 @@ Parameter name: arrayIndex")]
Assert.AreEqual(p4, l[1]);
}
#if !PocketPC && !SILVERLIGHT
#if !PocketPC && !SILVERLIGHT && !NET20
[Test]
public void PropertyChanging()
{
@@ -35,6 +35,7 @@ namespace Newtonsoft.Json.Tests.Linq
{
public class JTokenReaderTest : TestFixtureBase
{
#if !PocketPC && !NET20
[Test]
public void YahooFinance()
{
@@ -109,6 +110,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsFalse(jsonReader.Read());
}
}
#endif
[Test]
public void ReadLineInfo()
@@ -194,5 +196,56 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(false, lineInfo.HasLineInfo());
}
}
[Test]
public void ReadBytes()
{
byte[] data = Encoding.UTF8.GetBytes("Hello world!");
JObject o =
new JObject(
new JProperty("Test1", data)
);
using (JTokenReader jsonReader = new JTokenReader(o))
{
jsonReader.Read();
Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType);
jsonReader.Read();
Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
Assert.AreEqual("Test1", jsonReader.Value);
byte[] readBytes = jsonReader.ReadAsBytes();
Assert.AreEqual(data, readBytes);
Assert.IsTrue(jsonReader.Read());
Assert.AreEqual(JsonToken.EndObject, jsonReader.TokenType);
Assert.IsFalse(jsonReader.Read());
}
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error reading bytes. Expected bytes but got Integer.")]
public void ReadBytesFailure()
{
JObject o =
new JObject(
new JProperty("Test1", 1)
);
using (JTokenReader jsonReader = new JTokenReader(o))
{
jsonReader.Read();
Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType);
jsonReader.Read();
Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
Assert.AreEqual("Test1", jsonReader.Value);
jsonReader.ReadAsBytes();
}
}
}
}
+12 -2
View File
@@ -196,7 +196,7 @@ namespace Newtonsoft.Json.Tests.Linq
public void Casting()
{
Assert.AreEqual(new DateTime(2000, 12, 20), (DateTime)new JValue(new DateTime(2000, 12, 20)));
#if !PocketPC
#if !PocketPC && !NET20
Assert.AreEqual(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)));
Assert.AreEqual(null, (DateTimeOffset?)new JValue((DateTimeOffset?)null));
Assert.AreEqual(null, (DateTimeOffset?)(JValue)null);
@@ -240,13 +240,16 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(5f, (float)(new JValue(5L)));
Assert.AreEqual(5f, (float)(new JValue(5m)));
Assert.AreEqual(5f, (float?)(new JValue(5m)));
byte[] data = new byte[0];
Assert.AreEqual(data, (byte[])(new JValue(data)));
}
[Test]
public void ImplicitCastingTo()
{
Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTime(2000, 12, 20)), (JValue)new DateTime(2000, 12, 20)));
#if !PocketPC
#if !PocketPC && !NET20
Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)), (JValue)new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)));
Assert.IsTrue(JToken.DeepEquals(new JValue((DateTimeOffset?)null), (JValue)(DateTimeOffset?)null));
#endif
@@ -269,6 +272,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(JToken.DeepEquals(new JValue(ushort.MaxValue), (JValue)ushort.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(11.1f), (JValue)11.1f));
Assert.IsTrue(JToken.DeepEquals(new JValue(float.MinValue), (JValue)float.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(double.MinValue), (JValue)double.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(uint.MaxValue), (JValue)uint.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MaxValue), (JValue)ulong.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MinValue), (JValue)ulong.MinValue));
@@ -281,7 +285,13 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(JToken.DeepEquals(new JValue(double.MaxValue), (JValue)(double?)double.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue((object)null), (JValue)(double?)null));
Assert.IsFalse(JToken.DeepEquals(new JValue(true), (JValue)(bool?)null));
Assert.IsFalse(JToken.DeepEquals(new JValue((object)null), (JValue)(object)null));
byte[] emptyData = new byte[0];
Assert.IsTrue(JToken.DeepEquals(new JValue(emptyData), (JValue)emptyData));
Assert.IsFalse(JToken.DeepEquals(new JValue(emptyData), (JValue)new byte[1]));
Assert.IsTrue(JToken.DeepEquals(new JValue(Encoding.UTF8.GetBytes("Hi")), (JValue)Encoding.UTF8.GetBytes("Hi")));
}
[Test]
@@ -39,6 +39,8 @@ namespace Newtonsoft.Json.Tests.Linq
[Test]
public void ValueFormatting()
{
byte[] data = Encoding.UTF8.GetBytes("Hello world.");
JToken root;
using (JTokenWriter jsonWriter = new JTokenWriter())
{
@@ -55,13 +57,14 @@ namespace Newtonsoft.Json.Tests.Linq
jsonWriter.WriteValue("This is a string.");
jsonWriter.WriteNull();
jsonWriter.WriteUndefined();
jsonWriter.WriteValue(data);
jsonWriter.WriteEndArray();
root = jsonWriter.Token;
}
Assert.IsInstanceOfType(typeof(JArray), root);
Assert.AreEqual(12, root.Children().Count());
Assert.AreEqual(13, root.Children().Count());
Assert.AreEqual("@", (string)root[0]);
Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", (string)root[1]);
Assert.AreEqual(true, (bool)root[2]);
@@ -73,6 +76,8 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(string.Empty, (string)root[8]);
Assert.AreEqual("This is a string.", (string)root[9]);
Assert.AreEqual(null, ((JValue)root[10]).Value);
Assert.AreEqual(null, ((JValue)root[11]).Value);
Assert.AreEqual(data, (byte[])root[12]);
}
[Test]
@@ -100,6 +105,9 @@ namespace Newtonsoft.Json.Tests.Linq
jsonWriter.WriteValue("DVD read/writer");
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
jsonWriter.WriteValue(new byte[0]);
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
jsonWriter.WriteEnd();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
@@ -60,6 +60,12 @@ namespace Newtonsoft.Json.Tests.Linq
v.Value = DBNull.Value;
Assert.AreEqual(DBNull.Value, v.Value);
Assert.AreEqual(JTokenType.Null, v.Type);
byte[] data = new byte[0];
v.Value = data;
Assert.AreEqual(data, v.Value);
Assert.AreEqual(JTokenType.Bytes, v.Type);
}
[Test]
@@ -545,6 +545,7 @@ keyword such as type of business.""
Assert.AreEqual(null, c["purple"]);
}
#if !PocketPC && !NET20
[Test]
public void ToStringJsonConverter()
{
@@ -597,6 +598,7 @@ keyword such as type of business.""
Assert.AreEqual(4, jsonWriter.Token.Children().Count());
}
#endif
[Test]
public void FromObject()
@@ -683,9 +685,8 @@ keyword such as type of business.""
o =
new JObject(
new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)),
new JProperty("Test2", new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0))),
new JProperty("Test3", "Test3Value"),
new JProperty("Test4", null)
new JProperty("Test2", "Test2Value"),
new JProperty("Test3", null)
);
enumerable = o.AsJEnumerable();
@@ -83,6 +83,8 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Bson\BsonWriterTests.cs" />
<Compile Include="Bson\BsonReaderTests.cs" />
<Compile Include="Converters\BinaryConverterTests.cs" />
<Compile Include="Converters\DataTableConverterTests.cs" />
<Compile Include="Converters\DataSetConverterTests.cs" />
@@ -428,7 +428,6 @@ keyword such as type of business.""
result = JsonConvert.SerializeObject(testDates);
Assert.AreEqual(expected, result);
}
#endif
[Test]
public void DateTimeOffset()
@@ -443,6 +442,7 @@ keyword such as type of business.""
string result = JsonConvert.SerializeObject(testDates);
Assert.AreEqual(@"[""\/Date(-59011455539000+0000)\/"",""\/Date(946688461000+0000)\/"",""\/Date(946641661000+1300)\/"",""\/Date(946701061000-0330)\/""]", result);
}
#endif
[Test]
public void NonStringKeyDictionary()
@@ -1715,6 +1715,7 @@ keyword such as type of business.""
Assert.AreEqual("Product 1", products[0].Name);
}
#if !PocketPC && !NET20
[Test]
public void DeserializeEmptyStringToNullableDateTime()
{
@@ -1723,6 +1724,7 @@ keyword such as type of business.""
NullableDateTimeTestClass c = JsonConvert.DeserializeObject<NullableDateTimeTestClass>(json);
Assert.AreEqual(null, c.DateTimeField);
}
#endif
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Event. A class should either have a default constructor or only one constructor with arguments.")]
@@ -1911,5 +1913,85 @@ keyword such as type of business.""
Assert.AreEqual(structTest.IntProperty, deserialized.IntProperty);
Assert.AreEqual(structTest.IntField, deserialized.IntField);
}
public class ListOfIds<T> : JsonConverter where T : Bar, new()
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
IList<T> list = (IList<T>) value;
writer.WriteStartArray();
foreach (T item in list)
{
writer.WriteValue(item.Id);
}
writer.WriteEndArray();
}
public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
{
IList<T> list = new List<T>();
reader.Read();
while (reader.TokenType != JsonToken.EndArray)
{
long id = (long)reader.Value;
list.Add(new T
{
Id = Convert.ToInt32(id)
});
reader.Read();
}
return list;
}
public override bool CanConvert(Type objectType)
{
return typeof (IList<T>).IsAssignableFrom(objectType);
}
}
public class Foo
{
public Foo()
{
Bars = new List<Bar>();
}
[JsonConverter(typeof(ListOfIds<Bar>))]
public List<Bar> Bars { get; set; }
}
public class Bar
{
public int Id { get; set; }
}
[Test]
public void SerializeListWithJsonConverter()
{
Foo f = new Foo();
f.Bars.Add(new Bar { Id = 0 });
f.Bars.Add(new Bar { Id = 1 });
f.Bars.Add(new Bar { Id = 2 });
string json = JsonConvert.SerializeObject(f, Formatting.Indented);
Assert.AreEqual(@"{
""Bars"": [
0,
1,
2
]
}", json);
Foo newFoo = JsonConvert.DeserializeObject<Foo>(json);
Assert.AreEqual(3, newFoo.Bars.Count);
Assert.AreEqual(0, newFoo.Bars[0].Id);
Assert.AreEqual(1, newFoo.Bars[1].Id);
Assert.AreEqual(2, newFoo.Bars[2].Id);
}
}
}
@@ -1,4 +1,29 @@
using System;
#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.IO;
using System.Linq;
@@ -23,7 +48,7 @@ namespace Newtonsoft.Json.Tests.Serialization
//JsonConvert.ConvertDateTimeToJavaScriptTicks(s1.Establised.DateTime)
Assert.AreEqual(@"{""Color"":4,""Establised"":""\/Date(1264122061000+0000)\/"",""Width"":1.1,""Employees"":999,""RoomsPerFloor"":[1,2,3,4,5,6,7,8,9],""Open"":false,""Symbol"":""@"",""Mottos"":[""Hello World"",""öäüÖÄÜ\\'{new Date(12345);}[222]_µ@²³~"",null,"" ""],""Cost"":100980.1,""Escape"":""\r\n\t\f\b?{\\r\\n\""'"",""product"":[{""Name"":""Rocket"",""ExpiryDate"":""\/Date(949532490000)\/"",""Price"":0.0},{""Name"":""Alien"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0.0}]}", sw.GetStringBuilder().ToString());
Assert.AreEqual(@"{""Color"":4,""Establised"":""\/Date(1264122061000)\/"",""Width"":1.1,""Employees"":999,""RoomsPerFloor"":[1,2,3,4,5,6,7,8,9],""Open"":false,""Symbol"":""@"",""Mottos"":[""Hello World"",""öäüÖÄÜ\\'{new Date(12345);}[222]_µ@²³~"",null,"" ""],""Cost"":100980.1,""Escape"":""\r\n\t\f\b?{\\r\\n\""'"",""product"":[{""Name"":""Rocket"",""ExpiryDate"":""\/Date(949532490000)\/"",""Price"":0.0},{""Name"":""Alien"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0.0}]}", sw.GetStringBuilder().ToString());
Store s2 = (Store)jsonSerializer.Deserialize(new JsonTextReader(new StringReader("{}")), typeof(Store));
Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", s2.Escape);
@@ -23,6 +23,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !PocketPC && !NET20
using System;
using System.Collections.Generic;
using System.Linq;
@@ -37,4 +38,5 @@ namespace Newtonsoft.Json.Tests.TestObjects
public DateTimeOffset DateTimeOffsetField { get; set; }
public string PostField { get; set; }
}
}
}
#endif
@@ -23,6 +23,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !PocketPC && !NET20
using System;
using System.Collections.Generic;
using System.Linq;
@@ -37,4 +38,5 @@ namespace Newtonsoft.Json.Tests.TestObjects
public DateTimeOffset? DateTimeOffsetField { get; set; }
public string PostField { get; set; }
}
}
}
#endif
@@ -31,7 +31,7 @@ namespace Newtonsoft.Json.Tests.TestObjects
public class Store
{
public StoreColor Color = StoreColor.Yellow;
public DateTimeOffset Establised = new DateTimeOffset(2010, 1, 22, 1, 1, 1, TimeSpan.Zero);
public DateTime Establised = new DateTime(2010, 1, 22, 1, 1, 1, DateTimeKind.Utc);
public double Width = 1.1;
public int Employees = 999;
public int[] RoomsPerFloor = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
@@ -61,4 +61,4 @@ namespace Newtonsoft.Json.Tests.TestObjects
product.Add(alien);
}
}
}
}