-Generic JsonConverter WIP + initial tests

This commit is contained in:
James Newton-King
2017-08-11 18:15:20 +12:00
parent 36cfb508b8
commit 0996a59f8c
6 changed files with 197 additions and 21 deletions
@@ -0,0 +1,156 @@
#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;
#if !(NET20 || DNXCORE50)
using System.Data.Linq;
#endif
#if !DNXCORE50
using System.Data.SqlTypes;
#endif
using System.Text;
using Newtonsoft.Json.Converters;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
namespace Newtonsoft.Json.Tests.Converters
{
[TestFixture]
public class GenericJsonConverterTests : TestFixtureBase
{
public class TestGenericConverter : JsonConverter<string>
{
public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer)
{
writer.WriteValue(value);
}
public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return (string)reader.Value + existingValue;
}
}
[Test]
public void WriteJsonObject()
{
StringWriter sw = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(sw);
TestGenericConverter converter = new TestGenericConverter();
converter.WriteJson(jsonWriter, (object)"String!", null);
Assert.AreEqual(@"""String!""", sw.ToString());
}
[Test]
public void WriteJsonGeneric()
{
StringWriter sw = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(sw);
TestGenericConverter converter = new TestGenericConverter();
converter.WriteJson(jsonWriter, "String!", null);
Assert.AreEqual(@"""String!""", sw.ToString());
}
[Test]
public void WriteJsonBadType()
{
StringWriter sw = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(sw);
TestGenericConverter converter = new TestGenericConverter();
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
converter.WriteJson(jsonWriter, 123, null);
}, "Converter cannot write specified value to JSON. System.String is required.");
}
[Test]
public void ReadJsonGenericExistingValueNull()
{
StringReader sr = new StringReader("'String!'");
JsonTextReader jsonReader = new JsonTextReader(sr);
jsonReader.Read();
TestGenericConverter converter = new TestGenericConverter();
string s = converter.ReadJson(jsonReader, typeof(string), null, false, null);
Assert.AreEqual(@"String!", s);
}
[Test]
public void ReadJsonGenericExistingValueString()
{
StringReader sr = new StringReader("'String!'");
JsonTextReader jsonReader = new JsonTextReader(sr);
jsonReader.Read();
TestGenericConverter converter = new TestGenericConverter();
string s = converter.ReadJson(jsonReader, typeof(string), "Existing!", true, null);
Assert.AreEqual(@"String!Existing!", s);
}
[Test]
public void ReadJsonObjectExistingValueNull()
{
StringReader sr = new StringReader("'String!'");
JsonTextReader jsonReader = new JsonTextReader(sr);
jsonReader.Read();
TestGenericConverter converter = new TestGenericConverter();
string s = (string)converter.ReadJson(jsonReader, typeof(string), null, null);
Assert.AreEqual(@"String!", s);
}
[Test]
public void ReadJsonObjectExistingValueWrongType()
{
StringReader sr = new StringReader("'String!'");
JsonTextReader jsonReader = new JsonTextReader(sr);
jsonReader.Read();
TestGenericConverter converter = new TestGenericConverter();
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
converter.ReadJson(jsonReader, typeof(string), 12345, null);
}, "Converter cannot read JSON with the specified existing value. System.String is required.");
}
}
}
@@ -44,6 +44,12 @@ namespace Newtonsoft.Json.Converters
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, BsonObjectId value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
BsonWriter bsonWriter = writer as BsonWriter;
if (bsonWriter != null)
{
@@ -60,11 +66,11 @@ namespace Newtonsoft.Json.Converters
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingHasValue">The existing value has a value.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="existingValue">The existing value of object being read. If there is no existing value then <c>null</c> will be used.</param>
/// <param name="hasExistingValue">The existing value has a value.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override BsonObjectId ReadJson(JsonReader reader, Type objectType, bool existingHasValue, BsonObjectId existingValue, JsonSerializer serializer)
public override BsonObjectId ReadJson(JsonReader reader, Type objectType, BsonObjectId existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.Bytes)
{
@@ -43,6 +43,12 @@ namespace Newtonsoft.Json.Converters
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, DataSet value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
DataTableConverter converter = new DataTableConverter();
@@ -64,11 +70,11 @@ namespace Newtonsoft.Json.Converters
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingHasValue">The existing value has a value.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="existingValue">The existing value of object being read. If there is no existing value then <c>null</c> will be used.</param>
/// <param name="hasExistingValue">The existing value has a value.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override DataSet ReadJson(JsonReader reader, Type objectType, bool existingHasValue, DataSet existingValue, JsonSerializer serializer)
public override DataSet ReadJson(JsonReader reader, Type objectType, DataSet existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
@@ -47,6 +47,12 @@ namespace Newtonsoft.Json.Converters
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, DataTable value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartArray();
@@ -77,11 +83,11 @@ namespace Newtonsoft.Json.Converters
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingHasValue">The existing value has a value.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="existingValue">The existing value of object being read. If there is no existing value then <c>null</c> will be used.</param>
/// <param name="hasExistingValue">The existing value has a value.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override DataTable ReadJson(JsonReader reader, Type objectType, bool existingHasValue, DataTable existingValue, JsonSerializer serializer)
public override DataTable ReadJson(JsonReader reader, Type objectType, DataTable existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
@@ -90,7 +96,7 @@ namespace Newtonsoft.Json.Converters
DataTable dt = existingValue;
if (!existingHasValue)
if (!hasExistingValue)
{
// handle typed datasets
dt = (objectType == typeof(DataTable))
@@ -45,7 +45,9 @@ namespace Newtonsoft.Json.Converters
if (value == null)
{
writer.WriteNull();
return;
}
writer.WriteValue(value.ToString());
}
@@ -54,11 +56,11 @@ namespace Newtonsoft.Json.Converters
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingHasValue">The existing value has a value.</param>
/// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
/// <param name="existingValue">The existing value of object being read. If there is no existing value then <c>null</c> will be used.</param>
/// <param name="hasExistingValue">The existing value has a value.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override Version ReadJson(JsonReader reader, Type objectType, bool existingHasValue, Version existingValue, JsonSerializer serializer)
public override Version ReadJson(JsonReader reader, Type objectType, Version existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
+8 -8
View File
@@ -86,7 +86,7 @@ namespace Newtonsoft.Json
/// <summary>
/// Converts an object to and from JSON.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="T">The object type to convert.</typeparam>
public abstract class JsonConverter<T> : JsonConverter
{
/// <summary>
@@ -99,7 +99,7 @@ namespace Newtonsoft.Json
{
if (!(value != null ? value is T : ReflectionUtils.IsNullable(typeof(T))))
{
throw new JsonSerializationException("This converter cannot convert {0} of type {1}".FormatWith(CultureInfo.InvariantCulture, value, value?.GetType()));
throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
}
WriteJson(writer, (T)value, serializer);
}
@@ -122,12 +122,12 @@ namespace Newtonsoft.Json
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var existingIsNull = existingValue == null;
bool existingIsNull = existingValue == null;
if (!(existingIsNull || existingValue is T))
{
throw new JsonSerializationException("This converter cannot convert {0} of type {1}".FormatWith(CultureInfo.InvariantCulture, existingValue, existingValue.GetType()));
throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
}
return ReadJson(reader, objectType, !existingIsNull, existingIsNull ? default(T) : (T)existingValue, serializer);
return ReadJson(reader, objectType, existingIsNull ? default(T) : (T)existingValue, !existingIsNull, serializer);
}
/// <summary>
@@ -135,11 +135,11 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingHasValue">The existing value has a value.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="existingValue">The existing value of object being read. If there is no existing value then <c>null</c> will be used.</param>
/// <param name="hasExistingValue">The existing value has a value.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public abstract T ReadJson(JsonReader reader, Type objectType, bool existingHasValue, T existingValue, JsonSerializer serializer);
public abstract T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer);
/// <summary>
/// Determines whether this instance can convert the specified object type.