-Added StringEnumConverter

-Added BinaryConverter
This commit is contained in:
JamesNK
2009-03-29 01:36:06 +00:00
parent b9bedd1233
commit 3630a43f11
13 changed files with 530 additions and 8 deletions
@@ -0,0 +1,136 @@
using System;
using System.Collections.Generic;
#if !SILVERLIGHT && !PocketPC
using System.Data.Linq;
#endif
#if !SILVERLIGHT
using System.Data.SqlTypes;
#endif
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
using NUnit.Framework;
using Newtonsoft.Json.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Converters
{
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 !SILVERLIGHT && !PocketPC
[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);
}
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, new BinaryConverter());
Assert.AreEqual(@"{
""ByteArray"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
""NullByteArray"": null
}", json);
}
#if !SILVERLIGHT
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, new BinaryConverter());
Assert.AreEqual(TestData, byteArrayClass.ByteArray);
Assert.AreEqual(null, byteArrayClass.NullByteArray);
}
}
}
@@ -0,0 +1,161 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
using NUnit.Framework;
using Newtonsoft.Json.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Converters
{
public class StringEnumConverterTests : TestFixtureBase
{
public class EnumClass
{
public StoreColor StoreColor { get; set; }
public StoreColor? NullableStoreColor1 { get; set; }
public StoreColor? NullableStoreColor2 { get; set; }
}
public enum NegativeEnum
{
Negative = -1,
Zero = 0,
Positive = 1
}
public class NegativeEnumClass
{
public NegativeEnum Value1 { get; set; }
public NegativeEnum Value2 { get; set; }
}
[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 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);
}
}
}
@@ -604,7 +604,7 @@ keyword such as type of business.""
//JsonConvert.ConvertDateTimeToJavaScriptTicks(s1.Establised.DateTime)
Assert.AreEqual(@"{""Color"":2,""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},{""Name"":""Alien"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0}]}", sw.GetStringBuilder().ToString());
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},{""Name"":""Alien"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":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);
@@ -58,6 +58,8 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Converters\BinaryConverterTests.cs" />
<Compile Include="Converters\StringEnumConverterTests.cs" />
<Compile Include="Serialization\CamelCaseMappingResolverTests.cs" />
<Compile Include="JsonValidatingReaderTests.cs" />
<Compile Include="Schema\ExtensionsTests.cs" />
@@ -63,6 +63,8 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Converters\BinaryConverterTests.cs" />
<Compile Include="Converters\StringEnumConverterTests.cs" />
<Compile Include="Serialization\CamelCaseMappingResolverTests.cs" />
<Compile Include="JsonValidatingReaderTests.cs" />
<Compile Include="Schema\ExtensionsTests.cs" />
@@ -57,6 +57,9 @@
<Reference Include="System.Data.Entity">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Runtime.Serialization">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
@@ -77,6 +80,8 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Converters\BinaryConverterTests.cs" />
<Compile Include="Converters\StringEnumConverterTests.cs" />
<Compile Include="JsonValidatingReaderTests.cs" />
<Compile Include="Schema\ExtensionsTests.cs" />
<Compile Include="Schema\JsonSchemaModelBuilderTests.cs" />
@@ -23,13 +23,16 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json.Tests.TestObjects
{
[Flags]
public enum StoreColor
{
Black,
Red,
Yellow,
White
Black = 1,
Red = 2,
Yellow = 4,
White = 8
}
}
@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
#if !SILVERLIGHT && !PocketPC
using System.Data.Linq;
#endif
#if !SILVERLIGHT
using System.Data.SqlTypes;
#endif
using System.Linq;
using System.Text;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a binary value to and from a base 64 string value.
/// </summary>
public class BinaryConverter : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
public override void WriteJson(JsonWriter writer, object value)
{
if (value == null)
{
writer.WriteNull();
return;
}
byte[] data = value as byte[];
if (data == null)
data = GetByteArray(value);
writer.WriteValue(Convert.ToBase64String(data));
}
private byte[] GetByteArray(object value)
{
#if !SILVERLIGHT && !PocketPC
if (value is Binary)
return ((Binary)value).ToArray();
#endif
#if !SILVERLIGHT
if (value is SqlBinary)
return ((SqlBinary) value).Value;
#endif
throw new Exception("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType)
{
Type t = (ReflectionUtils.IsNullableType(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullable(objectType))
throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
return null;
}
if (reader.TokenType != JsonToken.String)
throw new Exception("Unexpected token parsing binary. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
string encodedData = reader.Value.ToString();
byte[] data = Convert.FromBase64String(encodedData);
if (t == typeof(byte[]))
return data;
#if !SILVERLIGHT && !PocketPC
if (typeof(Binary).IsAssignableFrom(t))
return new Binary(data);
#endif
#if !SILVERLIGHT
if (typeof(SqlBinary).IsAssignableFrom(t))
return new SqlBinary(data);
#endif
throw new Exception("Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType));
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
Type t = (ReflectionUtils.IsNullableType(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
if (t == typeof(byte[]))
return true;
#if !SILVERLIGHT && !PocketPC
if (typeof(Binary).IsAssignableFrom(t))
return true;
#endif
#if !SILVERLIGHT
if (typeof(SqlBinary).IsAssignableFrom(t))
return true;
#endif
return false;
}
}
}
@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts an <see cref="Enum"/> to and from its name string value.
/// </summary>
public class StringEnumConverter : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
public override void WriteJson(JsonWriter writer, object value)
{
if (value == null)
{
writer.WriteNull();
return;
}
Enum e = (Enum) value;
string enumName = e.ToString("G");
if (char.IsNumber(enumName[0]) || enumName[0] == '-')
writer.WriteValue(value);
else
writer.WriteValue(enumName);
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType)
{
Type t = (ReflectionUtils.IsNullableType(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullableType(objectType))
throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
return null;
}
if (reader.TokenType == JsonToken.String)
return Enum.Parse(t, reader.Value.ToString(), true);
if (reader.TokenType == JsonToken.Integer)
return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t);
throw new Exception("Unexpected token when parsing enum. Expected String or Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
Type t = (ReflectionUtils.IsNullableType(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
return t.IsEnum;
}
}
}
@@ -55,6 +55,8 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Converters\BinaryConverter.cs" />
<Compile Include="Converters\StringEnumConverter.cs" />
<Compile Include="DateTimeOffset.cs" />
<Compile Include="IJsonLineInfo.cs" />
<Compile Include="JsonArrayAttribute.cs" />
@@ -48,9 +48,11 @@
<Reference Include="System.Windows.Browser" />
</ItemGroup>
<ItemGroup>
<Compile Include="Converters\BinaryConverter.cs" />
<Compile Include="Converters\IsoDateTimeConverter.cs" />
<Compile Include="Converters\JavaScriptDateTimeConverter.cs" />
<Compile Include="Converters\JsonDateTimeSerializationMode.cs" />
<Compile Include="Converters\StringEnumConverter.cs" />
<Compile Include="Converters\XmlNodeConverter.cs" />
<Compile Include="Converters\HtmlColorConverter.cs" />
<Compile Include="DateTimeOffset.cs" />
@@ -69,11 +69,16 @@
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Data.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Web" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Converters\BinaryConverter.cs" />
<Compile Include="Converters\StringEnumConverter.cs" />
<Compile Include="IJsonLineInfo.cs" />
<Compile Include="JsonArrayAttribute.cs" />
<Compile Include="JsonContainerAttribute.cs" />
+1 -3
View File
@@ -24,8 +24,6 @@
#endregion
using System;
using System.Collections.Generic;
using System.Text;
namespace Newtonsoft.Json
{
@@ -37,7 +35,7 @@ namespace Newtonsoft.Json
private char[] _buffer;
private int _position;
private static char[] _emptyBuffer = new char[0];
private static readonly char[] _emptyBuffer = new char[0];
public int Position
{