-Added JsonValueConverter

-Removed SecurityTransparentAttribute from WinRT build
This commit is contained in:
James Newton-King
2012-08-15 01:01:59 -07:00
parent 693d1d5d3e
commit 6db6db2b40
9 changed files with 573 additions and 4 deletions
@@ -0,0 +1,344 @@
#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;
using Windows.Data.Json;
using System.IO;
using System.Diagnostics;
using Newtonsoft.Json.Linq;
#endif
namespace Newtonsoft.Json.Tests.Converters
{
[TestFixture]
public class JsonValueConverterTests : TestFixtureBase
{
[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 DeserializePerformance()
{
Stopwatch timer = new Stopwatch();
timer.Start();
for (int i = 0; i < 100000; i++)
{
JsonObject o = JsonObject.Parse(@"{
""CPU"": ""Intel"",
""Drives"": [
""DVD read/writer"",
""500 gigabyte hard drive""
]
}");
}
timer.Stop();
string winrt = timer.Elapsed.TotalSeconds.ToString();
timer = new Stopwatch();
timer.Start();
for (int i = 0; i < 100000; i++)
{
JObject o = JObject.Parse(@"{
""CPU"": ""Intel"",
""Drives"": [
""DVD read/writer"",
""500 gigabyte hard drive""
]
}");
}
timer.Stop();
string linq = timer.Elapsed.TotalSeconds.ToString();
timer = new Stopwatch();
timer.Start();
for (int i = 0; i < 100000; i++)
{
JsonObject o = JsonConvert.DeserializeObject<JsonObject>(@"{
""CPU"": ""Intel"",
""Drives"": [
""DVD read/writer"",
""500 gigabyte hard drive""
]
}");
}
timer.Stop();
string jsonnet = timer.Elapsed.TotalSeconds.ToString();
throw new Exception(string.Format("winrt: {0}, jsonnet: {1}, jsonnet linq: {2}", winrt, jsonnet, linq));
Console.WriteLine(winrt);
Console.WriteLine(jsonnet);
}
//[Test]
public void SerializePerformance()
{
JsonObject o = JsonObject.Parse(@"{
""CPU"": ""Intel"",
""Drives"": [
""DVD read/writer"",
""500 gigabyte hard drive""
]
}");
JObject o1 = JObject.Parse(@"{
""CPU"": ""Intel"",
""Drives"": [
""DVD read/writer"",
""500 gigabyte hard drive""
]
}");
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));
Console.WriteLine(winrt);
Console.WriteLine(jsonnet);
}
}
}
@@ -124,6 +124,7 @@
<Compile Include="Converters\ExpandoObjectConverterTests.cs" />
<Compile Include="Converters\IsoDateTimeConverterTests.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverterTests.cs" />
<Compile Include="Converters\JsonValueConverterTests.cs" />
<Compile Include="Converters\ObjectIdConverterTests.cs" />
<Compile Include="Converters\RegexConverterTests.cs" />
<Compile Include="Converters\StringEnumConverterTests.cs" />
@@ -37,6 +37,10 @@ using System.Security;
[assembly: AssemblyTitle("Json.NET Tests Silverlight")]
#elif PocketPC
[assembly: AssemblyTitle("Json.NET Tests Compact")]
#elif PORTABLE
[assembly: AssemblyTitle("Json.NET Tests Portable")]
#elif NETFX_CORE
[assembly: AssemblyTitle("Json.NET Tests Metro")]
#elif NET20
[assembly: AssemblyTitle("Json.NET Tests .NET 2.0")]
#elif NET35
@@ -72,5 +76,5 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")]
#if !PocketPC
[assembly: AssemblyFileVersion("4.5.8.15205")]
[assembly: AssemblyFileVersion("4.5.8.15215")]
#endif
@@ -7139,6 +7139,29 @@ Parameter name: value",
Assert.AreEqual(2, values2.Count);
Assert.AreEqual("EventName!", values2[0][0, 0].EventName);
}
#if NETFX_CORE
[Test]
public void SerializeWinRTJsonObject()
{
var o = Windows.Data.Json.JsonObject.Parse(@"{
""CPU"": ""Intel"",
""Drives"": [
""DVD read/writer"",
""500 gigabyte hard drive""
]
}");
string json = JsonConvert.SerializeObject(o, Formatting.Indented);
Assert.AreEqual(@"{
""Drives"": [
""DVD read/writer"",
""500 gigabyte hard drive""
],
""CPU"": ""Intel""
}", json);
}
#endif
}
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
@@ -0,0 +1,193 @@
#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.Security;
using Newtonsoft.Json.Utilities;
using Windows.Data.Json;
namespace Newtonsoft.Json.Converters
{
public class JsonValueConverter : JsonConverter
{
[SecuritySafeCritical]
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
WriteJsonValue(writer, (IJsonValue)value);
}
[SecuritySafeCritical]
private void WriteJsonValue(JsonWriter writer, IJsonValue value)
{
switch (value.ValueType)
{
case JsonValueType.Array:
{
JsonArray a = value.GetArray();
writer.WriteStartArray();
for (int i = 0; i < a.Count; i++)
{
WriteJsonValue(writer, a[i]);
}
writer.WriteEndArray();
}
break;
case JsonValueType.Boolean:
{
writer.WriteValue(value.GetBoolean());
}
break;
case JsonValueType.Null:
{
writer.WriteNull();
}
break;
case JsonValueType.Number:
{
writer.WriteValue(value.GetNumber());
}
break;
case JsonValueType.Object:
{
JsonObject o = value.GetObject();
writer.WriteStartObject();
foreach (KeyValuePair<string, IJsonValue> v in o)
{
writer.WritePropertyName(v.Key);
WriteJsonValue(writer, v.Value);
}
writer.WriteEndObject();
}
break;
case JsonValueType.String:
{
writer.WriteValue(value.GetString());
}
break;
default:
throw new ArgumentOutOfRangeException("ValueType");
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.None)
reader.Read();
IJsonValue value = CreateJsonValue(reader);
if (!objectType.IsAssignableFrom(value.GetType()))
throw JsonSerializationException.Create(reader, "Could not convert '{0}' to '{1}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), objectType));
return value;
}
private IJsonValue CreateJsonValue(JsonReader reader)
{
while (reader.TokenType == JsonToken.Comment)
{
if (!reader.Read())
throw JsonSerializationException.Create(reader, "Unexpected end.");
}
switch (reader.TokenType)
{
case JsonToken.StartObject:
{
return CreateJsonObject(reader);
}
case JsonToken.StartArray:
{
JsonArray a = new JsonArray();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.EndArray:
return a;
default:
IJsonValue value = CreateJsonValue(reader);
a.Add(value);
break;
}
}
}
break;
case JsonToken.Integer:
case JsonToken.Float:
return JsonValue.CreateNumberValue(Convert.ToDouble(reader.Value));
case JsonToken.String:
return JsonValue.CreateStringValue(reader.Value.ToString());
case JsonToken.Boolean:
return JsonValue.CreateBooleanValue(Convert.ToBoolean(reader.Value));
case JsonToken.Null:
// surely there is a better way to create a null value than this?
return JsonValue.Parse("null");
case JsonToken.Date:
return JsonValue.CreateStringValue(reader.Value.ToString());
case JsonToken.Bytes:
return JsonValue.CreateStringValue(reader.Value.ToString());
default:
throw JsonSerializationException.Create(reader, "Unexpected or unsupported token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
throw JsonSerializationException.Create(reader, "Unexpected end.");
}
private JsonObject CreateJsonObject(JsonReader reader)
{
JsonObject o = new JsonObject();
string propertyName = null;
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
propertyName = (string)reader.Value;
break;
case JsonToken.EndObject:
return o;
case JsonToken.Comment:
break;
default:
IJsonValue propertyValue = CreateJsonValue(reader);
o.Add(propertyName, propertyValue);
break;
}
}
throw JsonSerializationException.Create(reader, "Unexpected end.");
}
public override bool CanConvert(Type objectType)
{
return typeof(IJsonValue).IsAssignableFrom(objectType);
}
}
}
+2 -1
View File
@@ -58,7 +58,6 @@ namespace Newtonsoft.Json.Linq
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
internal ListChangedEventHandler _listChanged;
internal AddingNewEventHandler _addingNew;
internal NotifyCollectionChangedEventHandler _collectionChanged;
/// <summary>
/// Occurs when the list changes or an item in the list changes.
@@ -79,6 +78,8 @@ namespace Newtonsoft.Json.Linq
}
#endif
#if SILVERLIGHT || !(NET20 || NET35 || PORTABLE)
internal NotifyCollectionChangedEventHandler _collectionChanged;
/// <summary>
/// Occurs when the items list of the collection has changed, or the collection is reset.
/// </summary>
@@ -127,6 +127,7 @@
<Compile Include="Converters\ExpandoObjectConverter.cs" />
<Compile Include="Converters\IsoDateTimeConverter.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverter.cs" />
<Compile Include="Converters\JsonValueConverter.cs" />
<Compile Include="Converters\KeyValuePairConverter.cs" />
<Compile Include="Converters\RegexConverter.cs" />
<Compile Include="Converters\StringEnumConverter.cs" />
@@ -42,7 +42,6 @@ using System.Security;
[assembly: AssemblyTitle("Json.NET Portable")]
#elif NETFX_CORE
[assembly: AssemblyTitle("Json.NET Metro")]
[assembly: SecurityTransparent]
#elif NET20
[assembly: AssemblyTitle("Json.NET .NET 2.0")]
[assembly: AllowPartiallyTrustedCallers]
@@ -91,7 +90,7 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")]
#if !PocketPC
[assembly: AssemblyFileVersion("4.5.8.15205")]
[assembly: AssemblyFileVersion("4.5.8.15215")]
#endif
[assembly: CLSCompliant(true)]
@@ -110,6 +110,9 @@ namespace Newtonsoft.Json.Serialization
new BinaryConverter(),
new DataSetConverter(),
new DataTableConverter(),
#endif
#if NETFX_CORE
new JsonValueConverter(),
#endif
new KeyValuePairConverter(),
new BsonObjectIdConverter()