-Code reformat

This commit is contained in:
James Newton-King
2013-10-20 15:08:39 +13:00
parent d03963016e
commit bcd6982419
466 changed files with 71645 additions and 71598 deletions
+129 -128
View File
@@ -33,150 +33,151 @@ using System.Collections.Generic;
namespace Newtonsoft.Json.Converters
{
#if !NET20
internal interface IBinary
{
byte[] ToArray();
}
#endif
/// <summary>
/// Converts a binary value to and from a base 64 string value.
/// </summary>
public class BinaryConverter : JsonConverter
{
#if !NET20
private const string BinaryTypeName = "System.Data.Linq.Binary";
internal interface IBinary
{
byte[] ToArray();
}
#endif
/// <summary>
/// Writes the JSON representation of the object.
/// Converts a binary value to and from a base 64 string value.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public class BinaryConverter : JsonConverter
{
if (value == null)
{
writer.WriteNull();
return;
}
byte[] data = GetByteArray(value);
writer.WriteValue(data);
}
private byte[] GetByteArray(object value)
{
#if !(NET20)
if (value.GetType().AssignableToTypeName(BinaryTypeName))
{
IBinary binary = DynamicWrapper.CreateWrapper<IBinary>(value);
return binary.ToArray();
}
#endif
if (value is SqlBinary)
return ((SqlBinary) value).Value;
throw new JsonSerializationException("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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Type t = (ReflectionUtils.IsNullableType(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullable(objectType))
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
return null;
}
byte[] data;
if (reader.TokenType == JsonToken.StartArray)
{
data = ReadByteArray(reader);
}
else if (reader.TokenType == JsonToken.String)
{
// current token is already at base64 string
// unable to call ReadAsBytes so do it the old fashion way
string encodedData = reader.Value.ToString();
data = Convert.FromBase64String(encodedData);
}
else
{
throw JsonSerializationException.Create(reader, "Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
#if !NET20
if (t.AssignableToTypeName(BinaryTypeName))
return Activator.CreateInstance(t, data);
private const string BinaryTypeName = "System.Data.Linq.Binary";
#endif
if (t == typeof(SqlBinary))
return new SqlBinary(data);
throw JsonSerializationException.Create(reader, "Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType));
}
private byte[] ReadByteArray(JsonReader reader)
{
List<byte> byteList = new List<byte>();
while (reader.Read())
{
switch (reader.TokenType)
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
case JsonToken.Integer:
byteList.Add(Convert.ToByte(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.EndArray:
return byteList.ToArray();
case JsonToken.Comment:
// skip
break;
default:
throw JsonSerializationException.Create(reader, "Unexpected token when reading bytes: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
if (value == null)
{
writer.WriteNull();
return;
}
byte[] data = GetByteArray(value);
writer.WriteValue(data);
}
}
throw JsonSerializationException.Create(reader, "Unexpected end when reading bytes.");
}
private byte[] GetByteArray(object value)
{
#if !(NET20)
if (value.GetType().AssignableToTypeName(BinaryTypeName))
{
IBinary binary = DynamicWrapper.CreateWrapper<IBinary>(value);
return binary.ToArray();
}
#endif
if (value is SqlBinary)
return ((SqlBinary)value).Value;
throw new JsonSerializationException("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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Type t = (ReflectionUtils.IsNullableType(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullable(objectType))
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
return null;
}
byte[] data;
if (reader.TokenType == JsonToken.StartArray)
{
data = ReadByteArray(reader);
}
else if (reader.TokenType == JsonToken.String)
{
// current token is already at base64 string
// unable to call ReadAsBytes so do it the old fashion way
string encodedData = reader.Value.ToString();
data = Convert.FromBase64String(encodedData);
}
else
{
throw JsonSerializationException.Create(reader, "Unexpected token parsing binary. Expected String or StartArray, 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)
{
#if !NET20
if (objectType.AssignableToTypeName(BinaryTypeName))
return true;
if (t.AssignableToTypeName(BinaryTypeName))
return Activator.CreateInstance(t, data);
#endif
if (objectType == typeof(SqlBinary) || objectType == typeof(SqlBinary?))
return true;
if (t == typeof(SqlBinary))
return new SqlBinary(data);
return false;
throw JsonSerializationException.Create(reader, "Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType));
}
private byte[] ReadByteArray(JsonReader reader)
{
List<byte> byteList = new List<byte>();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Integer:
byteList.Add(Convert.ToByte(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.EndArray:
return byteList.ToArray();
case JsonToken.Comment:
// skip
break;
default:
throw JsonSerializationException.Create(reader, "Unexpected token when reading bytes: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
}
throw JsonSerializationException.Create(reader, "Unexpected end when reading bytes.");
}
/// <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)
{
#if !NET20
if (objectType.AssignableToTypeName(BinaryTypeName))
return true;
#endif
if (objectType == typeof(SqlBinary) || objectType == typeof(SqlBinary?))
return true;
return false;
}
}
}
}
#endif
@@ -30,60 +30,60 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="BsonObjectId"/> to and from JSON and BSON.
/// </summary>
public class BsonObjectIdConverter : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// Converts a <see cref="BsonObjectId"/> to and from JSON and BSON.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public class BsonObjectIdConverter : JsonConverter
{
BsonObjectId objectId = (BsonObjectId) value;
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
BsonObjectId objectId = (BsonObjectId)value;
BsonWriter bsonWriter = writer as BsonWriter;
if (bsonWriter != null)
{
bsonWriter.WriteObjectId(objectId.Value);
}
else
{
writer.WriteValue(objectId.Value);
}
BsonWriter bsonWriter = writer as BsonWriter;
if (bsonWriter != null)
{
bsonWriter.WriteObjectId(objectId.Value);
}
else
{
writer.WriteValue(objectId.Value);
}
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.Bytes)
throw new JsonSerializationException("Expected Bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
byte[] value = (byte[])reader.Value;
return new BsonObjectId(value);
}
/// <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)
{
return (objectType == typeof(BsonObjectId));
}
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.Bytes)
throw new JsonSerializationException("Expected Bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
byte[] value = (byte[])reader.Value;
return new BsonObjectId(value);
}
/// <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)
{
return (objectType == typeof (BsonObjectId));
}
}
}
@@ -28,72 +28,72 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Create a custom object
/// </summary>
/// <typeparam name="T">The object type to convert.</typeparam>
public abstract class CustomCreationConverter<T> : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// Create a custom object
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
/// <typeparam name="T">The object type to convert.</typeparam>
public abstract class CustomCreationConverter<T> : JsonConverter
{
throw new NotSupportedException("CustomCreationConverter should only be used while deserializing.");
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotSupportedException("CustomCreationConverter should only be used while deserializing.");
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
T value = Create(objectType);
if (value == null)
throw new JsonSerializationException("No object created.");
serializer.Populate(reader, value);
return value;
}
/// <summary>
/// Creates an object which will then be populated by the serializer.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>The created object.</returns>
public abstract T Create(Type 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)
{
return typeof(T).IsAssignableFrom(objectType);
}
/// <summary>
/// Gets a value indicating whether this <see cref="JsonConverter"/> can write JSON.
/// </summary>
/// <value>
/// <c>true</c> if this <see cref="JsonConverter"/> can write JSON; otherwise, <c>false</c>.
/// </value>
public override bool CanWrite
{
get { return false; }
}
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
T value = Create(objectType);
if (value == null)
throw new JsonSerializationException("No object created.");
serializer.Populate(reader, value);
return value;
}
/// <summary>
/// Creates an object which will then be populated by the serializer.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>The created object.</returns>
public abstract T Create(Type 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)
{
return typeof (T).IsAssignableFrom(objectType);
}
/// <summary>
/// Gets a value indicating whether this <see cref="JsonConverter"/> can write JSON.
/// </summary>
/// <value>
/// <c>true</c> if this <see cref="JsonConverter"/> can write JSON; otherwise, <c>false</c>.
/// </value>
public override bool CanWrite
{
get { return false; }
}
}
}
@@ -30,82 +30,83 @@ using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="DataSet"/> to and from JSON.
/// </summary>
public class DataSetConverter : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// Converts a <see cref="DataSet"/> to and from JSON.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public class DataSetConverter : JsonConverter
{
DataSet dataSet = (DataSet)value;
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
DataSet dataSet = (DataSet)value;
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
DataTableConverter converter = new DataTableConverter();
DataTableConverter converter = new DataTableConverter();
writer.WriteStartObject();
writer.WriteStartObject();
foreach (DataTable table in dataSet.Tables)
{
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(table.TableName) : table.TableName);
converter.WriteJson(writer, table, serializer);
}
foreach (DataTable table in dataSet.Tables)
{
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(table.TableName) : table.TableName);
writer.WriteEndObject();
converter.WriteJson(writer, table, serializer);
}
writer.WriteEndObject();
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// handle typed datasets
DataSet ds = (objectType == typeof(DataSet))
? new DataSet()
: (DataSet)Activator.CreateInstance(objectType);
DataTableConverter converter = new DataTableConverter();
reader.Read();
while (reader.TokenType == JsonToken.PropertyName)
{
DataTable dt = ds.Tables[(string)reader.Value];
bool exists = (dt != null);
dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer);
if (!exists)
ds.Tables.Add(dt);
reader.Read();
}
return ds;
}
/// <summary>
/// Determines whether this instance can convert the specified value type.
/// </summary>
/// <param name="valueType">Type of the value.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type valueType)
{
return typeof(DataSet).IsAssignableFrom(valueType);
}
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// handle typed datasets
DataSet ds = (objectType == typeof(DataSet))
? new DataSet()
: (DataSet)Activator.CreateInstance(objectType);
DataTableConverter converter = new DataTableConverter();
reader.Read();
while (reader.TokenType == JsonToken.PropertyName)
{
DataTable dt = ds.Tables[(string)reader.Value];
bool exists = (dt != null);
dt = (DataTable)converter.ReadJson(reader, typeof (DataTable), dt, serializer);
if (!exists)
ds.Tables.Add(dt);
reader.Read();
}
return ds;
}
/// <summary>
/// Determines whether this instance can convert the specified value type.
/// </summary>
/// <param name="valueType">Type of the value.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type valueType)
{
return typeof(DataSet).IsAssignableFrom(valueType);
}
}
}
#endif
@@ -30,132 +30,133 @@ using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="DataTable"/> to and from JSON.
/// </summary>
public class DataTableConverter : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// Converts a <see cref="DataTable"/> to and from JSON.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public class DataTableConverter : JsonConverter
{
DataTable table = (DataTable)value;
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartArray();
foreach (DataRow row in table.Rows)
{
writer.WriteStartObject();
foreach (DataColumn column in row.Table.Columns)
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (serializer.NullValueHandling == NullValueHandling.Ignore && (row[column] == null || row[column] == DBNull.Value))
continue;
DataTable table = (DataTable)value;
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(column.ColumnName) : column.ColumnName);
serializer.Serialize(writer, row[column]);
}
writer.WriteEndObject();
}
writer.WriteStartArray();
writer.WriteEndArray();
}
foreach (DataRow row in table.Rows)
{
writer.WriteStartObject();
foreach (DataColumn column in row.Table.Columns)
{
if (serializer.NullValueHandling == NullValueHandling.Ignore && (row[column] == null || row[column] == DBNull.Value))
continue;
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
DataTable dt = existingValue as DataTable;
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(column.ColumnName) : column.ColumnName);
serializer.Serialize(writer, row[column]);
}
writer.WriteEndObject();
}
if (dt == null)
{
// handle typed datasets
dt = (objectType == typeof(DataTable))
? new DataTable()
: (DataTable)Activator.CreateInstance(objectType);
}
if (reader.TokenType == JsonToken.PropertyName)
{
dt.TableName = (string)reader.Value;
reader.Read();
}
reader.Read();
while (reader.TokenType == JsonToken.StartObject)
{
DataRow dr = dt.NewRow();
reader.Read();
while (reader.TokenType == JsonToken.PropertyName)
{
string columnName = (string)reader.Value;
reader.Read();
if (!dt.Columns.Contains(columnName))
{
Type columnType = GetColumnDataType(reader.TokenType);
dt.Columns.Add(new DataColumn(columnName, columnType));
}
dr[columnName] = reader.Value ?? DBNull.Value;
reader.Read();
writer.WriteEndArray();
}
dr.EndEdit();
dt.Rows.Add(dr);
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
DataTable dt = existingValue as DataTable;
reader.Read();
}
if (dt == null)
{
// handle typed datasets
dt = (objectType == typeof(DataTable))
? new DataTable()
: (DataTable)Activator.CreateInstance(objectType);
}
return dt;
if (reader.TokenType == JsonToken.PropertyName)
{
dt.TableName = (string)reader.Value;
reader.Read();
}
reader.Read();
while (reader.TokenType == JsonToken.StartObject)
{
DataRow dr = dt.NewRow();
reader.Read();
while (reader.TokenType == JsonToken.PropertyName)
{
string columnName = (string)reader.Value;
reader.Read();
if (!dt.Columns.Contains(columnName))
{
Type columnType = GetColumnDataType(reader.TokenType);
dt.Columns.Add(new DataColumn(columnName, columnType));
}
dr[columnName] = reader.Value ?? DBNull.Value;
reader.Read();
}
dr.EndEdit();
dt.Rows.Add(dr);
reader.Read();
}
return dt;
}
private static Type GetColumnDataType(JsonToken tokenType)
{
switch (tokenType)
{
case JsonToken.Integer:
return typeof(long);
case JsonToken.Float:
return typeof(double);
case JsonToken.String:
case JsonToken.Null:
case JsonToken.Undefined:
return typeof(string);
case JsonToken.Boolean:
return typeof(bool);
case JsonToken.Date:
return typeof(DateTime);
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Determines whether this instance can convert the specified value type.
/// </summary>
/// <param name="valueType">Type of the value.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type valueType)
{
return typeof(DataTable).IsAssignableFrom(valueType);
}
}
private static Type GetColumnDataType(JsonToken tokenType)
{
switch (tokenType)
{
case JsonToken.Integer:
return typeof (long);
case JsonToken.Float:
return typeof (double);
case JsonToken.String:
case JsonToken.Null:
case JsonToken.Undefined:
return typeof (string);
case JsonToken.Boolean:
return typeof (bool);
case JsonToken.Date:
return typeof (DateTime);
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Determines whether this instance can convert the specified value type.
/// </summary>
/// <param name="valueType">Type of the value.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type valueType)
{
return typeof(DataTable).IsAssignableFrom(valueType);
}
}
}
#endif
@@ -27,28 +27,28 @@ using System;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Provides a base class for converting a <see cref="DateTime"/> to and from JSON.
/// </summary>
public abstract class DateTimeConverterBase : JsonConverter
{
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// Provides a base class for converting a <see cref="DateTime"/> to and from JSON.
/// </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)
public abstract class DateTimeConverterBase : JsonConverter
{
if (objectType == typeof(DateTime) || objectType == typeof(DateTime?))
return true;
/// <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)
{
if (objectType == typeof(DateTime) || objectType == typeof(DateTime?))
return true;
#if !NET20
if (objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?))
return true;
if (objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?))
return true;
#endif
return false;
return false;
}
}
}
}
@@ -31,110 +31,111 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
internal interface IEntityKeyMember
{
string Key { get; set; }
object Value { get; set; }
}
/// <summary>
/// Converts an Entity Framework EntityKey to and from JSON.
/// </summary>
public class EntityKeyMemberConverter : JsonConverter
{
private const string EntityKeyMemberFullTypeName = "System.Data.EntityKeyMember";
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
internal interface IEntityKeyMember
{
IEntityKeyMember entityKeyMember = DynamicWrapper.CreateWrapper<IEntityKeyMember>(value);
Type keyType = (entityKeyMember.Value != null) ? entityKeyMember.Value.GetType() : null;
writer.WriteStartObject();
writer.WritePropertyName("Key");
writer.WriteValue(entityKeyMember.Key);
writer.WritePropertyName("Type");
writer.WriteValue((keyType != null) ? keyType.FullName : null);
writer.WritePropertyName("Value");
if (keyType != null)
{
string valueJson;
if (JsonSerializerInternalWriter.TryConvertToString(entityKeyMember.Value, keyType, out valueJson))
writer.WriteValue(valueJson);
else
writer.WriteValue(entityKeyMember.Value);
}
else
{
writer.WriteNull();
}
writer.WriteEndObject();
}
private static void ReadAndAssertProperty(JsonReader reader, string propertyName)
{
ReadAndAssert(reader);
if (reader.TokenType != JsonToken.PropertyName || reader.Value.ToString() != propertyName)
throw new JsonSerializationException("Expected JSON property '{0}'.".FormatWith(CultureInfo.InvariantCulture, propertyName));
}
private static void ReadAndAssert(JsonReader reader)
{
if (!reader.Read())
throw new JsonSerializationException("Unexpected end.");
string Key { get; set; }
object Value { get; set; }
}
/// <summary>
/// Reads the JSON representation of the object.
/// Converts an Entity Framework EntityKey to and from JSON.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public class EntityKeyMemberConverter : JsonConverter
{
IEntityKeyMember entityKeyMember = DynamicWrapper.CreateWrapper<IEntityKeyMember>(Activator.CreateInstance(objectType));
private const string EntityKeyMemberFullTypeName = "System.Data.EntityKeyMember";
ReadAndAssertProperty(reader, "Key");
ReadAndAssert(reader);
entityKeyMember.Key = reader.Value.ToString();
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
IEntityKeyMember entityKeyMember = DynamicWrapper.CreateWrapper<IEntityKeyMember>(value);
Type keyType = (entityKeyMember.Value != null) ? entityKeyMember.Value.GetType() : null;
ReadAndAssertProperty(reader, "Type");
ReadAndAssert(reader);
string type = reader.Value.ToString();
writer.WriteStartObject();
writer.WritePropertyName("Key");
writer.WriteValue(entityKeyMember.Key);
writer.WritePropertyName("Type");
writer.WriteValue((keyType != null) ? keyType.FullName : null);
Type t = Type.GetType(type);
writer.WritePropertyName("Value");
ReadAndAssertProperty(reader, "Value");
ReadAndAssert(reader);
entityKeyMember.Value = serializer.Deserialize(reader, t);
if (keyType != null)
{
string valueJson;
if (JsonSerializerInternalWriter.TryConvertToString(entityKeyMember.Value, keyType, out valueJson))
writer.WriteValue(valueJson);
else
writer.WriteValue(entityKeyMember.Value);
}
else
{
writer.WriteNull();
}
ReadAndAssert(reader);
writer.WriteEndObject();
}
return DynamicWrapper.GetUnderlyingObject(entityKeyMember);
private static void ReadAndAssertProperty(JsonReader reader, string propertyName)
{
ReadAndAssert(reader);
if (reader.TokenType != JsonToken.PropertyName || reader.Value.ToString() != propertyName)
throw new JsonSerializationException("Expected JSON property '{0}'.".FormatWith(CultureInfo.InvariantCulture, propertyName));
}
private static void ReadAndAssert(JsonReader reader)
{
if (!reader.Read())
throw new JsonSerializationException("Unexpected end.");
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
IEntityKeyMember entityKeyMember = DynamicWrapper.CreateWrapper<IEntityKeyMember>(Activator.CreateInstance(objectType));
ReadAndAssertProperty(reader, "Key");
ReadAndAssert(reader);
entityKeyMember.Key = reader.Value.ToString();
ReadAndAssertProperty(reader, "Type");
ReadAndAssert(reader);
string type = reader.Value.ToString();
Type t = Type.GetType(type);
ReadAndAssertProperty(reader, "Value");
ReadAndAssert(reader);
entityKeyMember.Value = serializer.Deserialize(reader, t);
ReadAndAssert(reader);
return DynamicWrapper.GetUnderlyingObject(entityKeyMember);
}
/// <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)
{
return (objectType.AssignableToTypeName(EntityKeyMemberFullTypeName));
}
}
/// <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)
{
return (objectType.AssignableToTypeName(EntityKeyMemberFullTypeName));
}
}
}
#endif
@@ -35,131 +35,131 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts an ExpandoObject to and from JSON.
/// </summary>
public class ExpandoObjectConverter : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// Converts an ExpandoObject to and from JSON.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public class ExpandoObjectConverter : JsonConverter
{
// can write is set to false
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return ReadValue(reader);
}
private object ReadValue(JsonReader reader)
{
while (reader.TokenType == JsonToken.Comment)
{
if (!reader.Read())
throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
}
switch (reader.TokenType)
{
case JsonToken.StartObject:
return ReadObject(reader);
case JsonToken.StartArray:
return ReadList(reader);
default:
if (JsonReader.IsPrimitiveToken(reader.TokenType))
return reader.Value;
throw JsonSerializationException.Create(reader, "Unexpected token when converting ExpandoObject: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
}
private object ReadList(JsonReader reader)
{
IList<object> list = new List<object>();
while (reader.Read())
{
switch (reader.TokenType)
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
case JsonToken.Comment:
break;
default:
object v = ReadValue(reader);
list.Add(v);
break;
case JsonToken.EndArray:
return list;
// can write is set to false
}
}
throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
}
private object ReadObject(JsonReader reader)
{
IDictionary<string, object> expandoObject = new ExpandoObject();
while (reader.Read())
{
switch (reader.TokenType)
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
case JsonToken.PropertyName:
string propertyName = reader.Value.ToString();
if (!reader.Read())
throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
object v = ReadValue(reader);
expandoObject[propertyName] = v;
break;
case JsonToken.Comment:
break;
case JsonToken.EndObject:
return expandoObject;
return ReadValue(reader);
}
}
throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
}
private object ReadValue(JsonReader reader)
{
while (reader.TokenType == JsonToken.Comment)
{
if (!reader.Read())
throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
}
/// <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)
{
return (objectType == typeof (ExpandoObject));
}
switch (reader.TokenType)
{
case JsonToken.StartObject:
return ReadObject(reader);
case JsonToken.StartArray:
return ReadList(reader);
default:
if (JsonReader.IsPrimitiveToken(reader.TokenType))
return reader.Value;
/// <summary>
/// Gets a value indicating whether this <see cref="JsonConverter"/> can write JSON.
/// </summary>
/// <value>
/// <c>true</c> if this <see cref="JsonConverter"/> can write JSON; otherwise, <c>false</c>.
/// </value>
public override bool CanWrite
{
get { return false; }
throw JsonSerializationException.Create(reader, "Unexpected token when converting ExpandoObject: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
}
private object ReadList(JsonReader reader)
{
IList<object> list = new List<object>();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Comment:
break;
default:
object v = ReadValue(reader);
list.Add(v);
break;
case JsonToken.EndArray:
return list;
}
}
throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
}
private object ReadObject(JsonReader reader)
{
IDictionary<string, object> expandoObject = new ExpandoObject();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string propertyName = reader.Value.ToString();
if (!reader.Read())
throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
object v = ReadValue(reader);
expandoObject[propertyName] = v;
break;
case JsonToken.Comment:
break;
case JsonToken.EndObject:
return expandoObject;
}
}
throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
}
/// <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)
{
return (objectType == typeof(ExpandoObject));
}
/// <summary>
/// Gets a value indicating whether this <see cref="JsonConverter"/> can write JSON.
/// </summary>
/// <value>
/// <c>true</c> if this <see cref="JsonConverter"/> can write JSON; otherwise, <c>false</c>.
/// </value>
public override bool CanWrite
{
get { return false; }
}
}
}
}
#endif
@@ -29,141 +29,141 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="DateTime"/> to and from the ISO 8601 date format (e.g. 2008-04-12T12:53Z).
/// </summary>
public class IsoDateTimeConverter : DateTimeConverterBase
{
private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
private string _dateTimeFormat;
private CultureInfo _culture;
/// <summary>
/// Gets or sets the date time styles used when converting a date to and from JSON.
/// Converts a <see cref="DateTime"/> to and from the ISO 8601 date format (e.g. 2008-04-12T12:53Z).
/// </summary>
/// <value>The date time styles used when converting a date to and from JSON.</value>
public DateTimeStyles DateTimeStyles
public class IsoDateTimeConverter : DateTimeConverterBase
{
get { return _dateTimeStyles; }
set { _dateTimeStyles = value; }
}
private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
/// <summary>
/// Gets or sets the date time format used when converting a date to and from JSON.
/// </summary>
/// <value>The date time format used when converting a date to and from JSON.</value>
public string DateTimeFormat
{
get { return _dateTimeFormat ?? string.Empty; }
set { _dateTimeFormat = StringUtils.NullEmptyString(value); }
}
private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
private string _dateTimeFormat;
private CultureInfo _culture;
/// <summary>
/// Gets or sets the culture used when converting a date to and from JSON.
/// </summary>
/// <value>The culture used when converting a date to and from JSON.</value>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.CurrentCulture; }
set { _culture = value; }
}
/// <summary>
/// Gets or sets the date time styles used when converting a date to and from JSON.
/// </summary>
/// <value>The date time styles used when converting a date to and from JSON.</value>
public DateTimeStyles DateTimeStyles
{
get { return _dateTimeStyles; }
set { _dateTimeStyles = value; }
}
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
string text;
/// <summary>
/// Gets or sets the date time format used when converting a date to and from JSON.
/// </summary>
/// <value>The date time format used when converting a date to and from JSON.</value>
public string DateTimeFormat
{
get { return _dateTimeFormat ?? string.Empty; }
set { _dateTimeFormat = StringUtils.NullEmptyString(value); }
}
if (value is DateTime)
{
DateTime dateTime = (DateTime)value;
/// <summary>
/// Gets or sets the culture used when converting a date to and from JSON.
/// </summary>
/// <value>The culture used when converting a date to and from JSON.</value>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.CurrentCulture; }
set { _culture = value; }
}
if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
|| (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
dateTime = dateTime.ToUniversalTime();
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
string text;
text = dateTime.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
}
if (value is DateTime)
{
DateTime dateTime = (DateTime)value;
if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
|| (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
dateTime = dateTime.ToUniversalTime();
text = dateTime.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
}
#if !NET20
else if (value is DateTimeOffset)
{
DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
|| (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
dateTimeOffset = dateTimeOffset.ToUniversalTime();
else if (value is DateTimeOffset)
{
DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
|| (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
dateTimeOffset = dateTimeOffset.ToUniversalTime();
text = dateTimeOffset.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
}
text = dateTimeOffset.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
}
#endif
else
{
throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)));
}
else
{
throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)));
}
writer.WriteValue(text);
}
writer.WriteValue(text);
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
bool nullable = ReflectionUtils.IsNullableType(objectType);
Type t = (nullable)
? Nullable.GetUnderlyingType(objectType)
: objectType;
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
bool nullable = ReflectionUtils.IsNullableType(objectType);
Type t = (nullable)
? Nullable.GetUnderlyingType(objectType)
: objectType;
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullableType(objectType))
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
return null;
}
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullableType(objectType))
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
if (reader.TokenType == JsonToken.Date)
{
return null;
}
if (reader.TokenType == JsonToken.Date)
{
#if !NET20
if (t == typeof(DateTimeOffset))
return new DateTimeOffset((DateTime)reader.Value);
if (t == typeof(DateTimeOffset))
return new DateTimeOffset((DateTime)reader.Value);
#endif
return reader.Value;
}
return reader.Value;
}
if (reader.TokenType != JsonToken.String)
throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
if (reader.TokenType != JsonToken.String)
throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
string dateText = reader.Value.ToString();
string dateText = reader.Value.ToString();
if (string.IsNullOrEmpty(dateText) && nullable)
return null;
if (string.IsNullOrEmpty(dateText) && nullable)
return null;
#if !NET20
if (t == typeof(DateTimeOffset))
{
if (!string.IsNullOrEmpty(_dateTimeFormat))
return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
else
return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
}
if (t == typeof(DateTimeOffset))
{
if (!string.IsNullOrEmpty(_dateTimeFormat))
return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
else
return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
}
#endif
if (!string.IsNullOrEmpty(_dateTimeFormat))
return DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
else
return DateTime.Parse(dateText, Culture, _dateTimeStyles);
if (!string.IsNullOrEmpty(_dateTimeFormat))
return DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
else
return DateTime.Parse(dateText, Culture, _dateTimeStyles);
}
}
}
}
@@ -29,90 +29,90 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="DateTime"/> to and from a JavaScript date constructor (e.g. new Date(52231943)).
/// </summary>
public class JavaScriptDateTimeConverter : DateTimeConverterBase
{
/// <summary>
/// Writes the JSON representation of the object.
/// Converts a <see cref="DateTime"/> to and from a JavaScript date constructor (e.g. new Date(52231943)).
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public class JavaScriptDateTimeConverter : DateTimeConverterBase
{
long ticks;
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
long ticks;
if (value is DateTime)
{
DateTime dateTime = (DateTime)value;
DateTime utcDateTime = dateTime.ToUniversalTime();
ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(utcDateTime);
}
if (value is DateTime)
{
DateTime dateTime = (DateTime)value;
DateTime utcDateTime = dateTime.ToUniversalTime();
ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(utcDateTime);
}
#if !NET20
else if (value is DateTimeOffset)
{
DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
DateTimeOffset utcDateTimeOffset = dateTimeOffset.ToUniversalTime();
ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(utcDateTimeOffset.UtcDateTime);
}
else if (value is DateTimeOffset)
{
DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
DateTimeOffset utcDateTimeOffset = dateTimeOffset.ToUniversalTime();
ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(utcDateTimeOffset.UtcDateTime);
}
#endif
else
{
throw new JsonSerializationException("Expected date object value.");
}
else
{
throw new JsonSerializationException("Expected date object value.");
}
writer.WriteStartConstructor("Date");
writer.WriteValue(ticks);
writer.WriteEndConstructor();
}
writer.WriteStartConstructor("Date");
writer.WriteValue(ticks);
writer.WriteEndConstructor();
}
/// <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>
/// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Type t = (ReflectionUtils.IsNullableType(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
/// <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>
/// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Type t = (ReflectionUtils.IsNullableType(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullable(objectType))
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullable(objectType))
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
return null;
}
return null;
}
if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
reader.Read();
reader.Read();
if (reader.TokenType != JsonToken.Integer)
throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
if (reader.TokenType != JsonToken.Integer)
throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
long ticks = (long)reader.Value;
long ticks = (long)reader.Value;
DateTime d = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);
DateTime d = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);
reader.Read();
reader.Read();
if (reader.TokenType != JsonToken.EndConstructor)
throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected EndConstructor, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
if (reader.TokenType != JsonToken.EndConstructor)
throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected EndConstructor, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
#if !NET20
if (t == typeof(DateTimeOffset))
return new DateTimeOffset(d);
if (t == typeof(DateTimeOffset))
return new DateTimeOffset(d);
#endif
return d;
return d;
}
}
}
}
@@ -23,6 +23,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if NETFX_CORE
using System;
using System.Collections.Generic;
@@ -33,192 +34,192 @@ using Windows.Data.Json;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="IJsonValue"/> to and from JSON.
/// </summary>
public class JsonValueConverter : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// Converts a <see cref="IJsonValue"/> to and from JSON.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public class JsonValueConverter : JsonConverter
{
WriteJsonValue(writer, (IJsonValue)value);
}
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
WriteJsonValue(writer, (IJsonValue)value);
}
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++)
private void WriteJsonValue(JsonWriter writer, IJsonValue value)
{
switch (value.ValueType)
{
WriteJsonValue(writer, a[i]);
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:
{
// JsonValue doesn't support integers
// serialize whole numbers without a decimal point
double d = value.GetNumber();
bool isInteger = (d % 1 == 0);
if (isInteger && d <= long.MaxValue && d >= long.MinValue)
writer.WriteValue(Convert.ToInt64(d));
else
writer.WriteValue(d);
}
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");
}
writer.WriteEndArray();
}
break;
case JsonValueType.Boolean:
{
writer.WriteValue(value.GetBoolean());
}
break;
case JsonValueType.Null:
{
writer.WriteNull();
}
break;
case JsonValueType.Number:
{
// JsonValue doesn't support integers
// serialize whole numbers without a decimal point
double d = value.GetNumber();
bool isInteger = (d % 1 == 0);
if (isInteger && d <= long.MaxValue && d >= long.MinValue)
writer.WriteValue(Convert.ToInt64(d));
else
writer.WriteValue(d);
}
break;
case JsonValueType.Object:
{
JsonObject o = value.GetObject();
writer.WriteStartObject();
foreach (KeyValuePair<string, IJsonValue> v in o)
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
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)
{
writer.WritePropertyName(v.Key);
WriteJsonValue(writer, v.Value);
if (!reader.Read())
throw JsonSerializationException.Create(reader, "Unexpected end.");
}
writer.WriteEndObject();
}
break;
case JsonValueType.String:
{
writer.WriteValue(value.GetString());
}
break;
default:
throw new ArgumentOutOfRangeException("ValueType");
}
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.None)
reader.Read();
switch (reader.TokenType)
{
case JsonToken.StartObject:
{
return CreateJsonObject(reader);
}
case JsonToken.StartArray:
{
JsonArray a = new JsonArray();
IJsonValue value = CreateJsonValue(reader);
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, CultureInfo.InvariantCulture));
case JsonToken.String:
return JsonValue.CreateStringValue(reader.Value.ToString());
case JsonToken.Boolean:
return JsonValue.CreateBooleanValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
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));
}
if (!objectType.IsAssignableFrom(value.GetType()))
throw JsonSerializationException.Create(reader, "Could not convert '{0}' to '{1}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), objectType));
throw JsonSerializationException.Create(reader, "Unexpected end.");
}
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();
private JsonObject CreateJsonObject(JsonReader reader)
{
JsonObject o = new JsonObject();
string propertyName = null;
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.EndArray:
return a;
default:
IJsonValue value = CreateJsonValue(reader);
a.Add(value);
break;
}
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;
}
}
}
break;
case JsonToken.Integer:
case JsonToken.Float:
return JsonValue.CreateNumberValue(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture));
case JsonToken.String:
return JsonValue.CreateStringValue(reader.Value.ToString());
case JsonToken.Boolean:
return JsonValue.CreateBooleanValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
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.");
}
}
throw JsonSerializationException.Create(reader, "Unexpected end.");
/// <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)
{
return typeof(IJsonValue).IsAssignableFrom(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)
{
return typeof(IJsonValue).IsAssignableFrom(objectType);
}
}
}
#endif
@@ -31,111 +31,111 @@ using System.Reflection;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="KeyValuePair{TKey,TValue}"/> to and from JSON.
/// </summary>
public class KeyValuePairConverter : JsonConverter
{
private const string KeyName = "Key";
private const string ValueName = "Value";
/// <summary>
/// Writes the JSON representation of the object.
/// Converts a <see cref="KeyValuePair{TKey,TValue}"/> to and from JSON.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public class KeyValuePairConverter : JsonConverter
{
Type t = value.GetType();
PropertyInfo keyProperty = t.GetProperty(KeyName);
PropertyInfo valueProperty = t.GetProperty(ValueName);
private const string KeyName = "Key";
private const string ValueName = "Value";
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyName) : KeyName);
serializer.Serialize(writer, ReflectionUtils.GetMemberValue(keyProperty, value));
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(ValueName) : ValueName);
serializer.Serialize(writer, ReflectionUtils.GetMemberValue(valueProperty, value));
writer.WriteEndObject();
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
bool isNullable = ReflectionUtils.IsNullableType(objectType);
if (reader.TokenType == JsonToken.Null)
{
if (!isNullable)
throw JsonSerializationException.Create(reader, "Cannot convert null value to KeyValuePair.");
return null;
}
Type t = (isNullable)
? Nullable.GetUnderlyingType(objectType)
: objectType;
IList<Type> genericArguments = t.GetGenericArguments();
Type keyType = genericArguments[0];
Type valueType = genericArguments[1];
object key = null;
object value = null;
reader.Read();
while (reader.TokenType == JsonToken.PropertyName)
{
string propertyName = reader.Value.ToString();
if (string.Equals(propertyName, KeyName, StringComparison.OrdinalIgnoreCase))
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
reader.Read();
key = serializer.Deserialize(reader, keyType);
}
else if (string.Equals(propertyName, ValueName, StringComparison.OrdinalIgnoreCase))
{
reader.Read();
value = serializer.Deserialize(reader, valueType);
}
else
{
reader.Skip();
Type t = value.GetType();
PropertyInfo keyProperty = t.GetProperty(KeyName);
PropertyInfo valueProperty = t.GetProperty(ValueName);
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyName) : KeyName);
serializer.Serialize(writer, ReflectionUtils.GetMemberValue(keyProperty, value));
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(ValueName) : ValueName);
serializer.Serialize(writer, ReflectionUtils.GetMemberValue(valueProperty, value));
writer.WriteEndObject();
}
reader.Read();
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
bool isNullable = ReflectionUtils.IsNullableType(objectType);
return Activator.CreateInstance(t, key, value);
if (reader.TokenType == JsonToken.Null)
{
if (!isNullable)
throw JsonSerializationException.Create(reader, "Cannot convert null value to KeyValuePair.");
return null;
}
Type t = (isNullable)
? Nullable.GetUnderlyingType(objectType)
: objectType;
IList<Type> genericArguments = t.GetGenericArguments();
Type keyType = genericArguments[0];
Type valueType = genericArguments[1];
object key = null;
object value = null;
reader.Read();
while (reader.TokenType == JsonToken.PropertyName)
{
string propertyName = reader.Value.ToString();
if (string.Equals(propertyName, KeyName, StringComparison.OrdinalIgnoreCase))
{
reader.Read();
key = serializer.Deserialize(reader, keyType);
}
else if (string.Equals(propertyName, ValueName, StringComparison.OrdinalIgnoreCase))
{
reader.Read();
value = serializer.Deserialize(reader, valueType);
}
else
{
reader.Skip();
}
reader.Read();
}
return Activator.CreateInstance(t, key, value);
}
/// <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.IsValueType() && t.IsGenericType())
return (t.GetGenericTypeDefinition() == typeof(KeyValuePair<,>));
return false;
}
}
/// <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.IsValueType() && t.IsGenericType())
return (t.GetGenericTypeDefinition() == typeof(KeyValuePair<,>));
return false;
}
}
}
+156 -156
View File
@@ -31,171 +31,171 @@ using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="Regex"/> to and from JSON and BSON.
/// </summary>
public class RegexConverter : JsonConverter
{
private const string PatternName = "Pattern";
private const string OptionsName = "Options";
/// <summary>
/// Writes the JSON representation of the object.
/// Converts a <see cref="Regex"/> to and from JSON and BSON.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public class RegexConverter : JsonConverter
{
Regex regex = (Regex) value;
private const string PatternName = "Pattern";
private const string OptionsName = "Options";
BsonWriter bsonWriter = writer as BsonWriter;
if (bsonWriter != null)
WriteBson(bsonWriter, regex);
else
WriteJson(writer, regex, serializer);
}
private bool HasFlag(RegexOptions options, RegexOptions flag)
{
return ((options & flag) == flag);
}
private void WriteBson(BsonWriter writer, Regex regex)
{
// Regular expression - The first cstring is the regex pattern, the second
// is the regex options string. Options are identified by characters, which
// must be stored in alphabetical order. Valid options are 'i' for case
// insensitive matching, 'm' for multiline matching, 'x' for verbose mode,
// 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode
// ('.' matches everything), and 'u' to make \w, \W, etc. match unicode.
string options = null;
if (HasFlag(regex.Options, RegexOptions.IgnoreCase))
options += "i";
if (HasFlag(regex.Options, RegexOptions.Multiline))
options += "m";
if (HasFlag(regex.Options, RegexOptions.Singleline))
options += "s";
options += "u";
if (HasFlag(regex.Options, RegexOptions.ExplicitCapture))
options += "x";
writer.WriteRegex(regex.ToString(), options);
}
private void WriteJson(JsonWriter writer, Regex regex, JsonSerializer serializer)
{
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(PatternName) : PatternName);
writer.WriteValue(regex.ToString());
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(OptionsName) : OptionsName);
serializer.Serialize(writer, regex.Options);
writer.WriteEndObject();
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartObject)
return ReadRegexObject(reader, serializer);
if (reader.TokenType == JsonToken.String)
return ReadRegexString(reader);
throw JsonSerializationException.Create(reader, "Unexpected token when reading Regex.");
}
private object ReadRegexString(JsonReader reader)
{
string regexText = (string)reader.Value;
int patternOptionDelimiterIndex = regexText.LastIndexOf('/');
string patternText = regexText.Substring(1, patternOptionDelimiterIndex - 1);
string optionsText = regexText.Substring(patternOptionDelimiterIndex + 1);
RegexOptions options = RegexOptions.None;
foreach (char c in optionsText)
{
switch (c)
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
case 'i':
options |= RegexOptions.IgnoreCase;
break;
case 'm':
options |= RegexOptions.Multiline;
break;
case 's':
options |= RegexOptions.Singleline;
break;
case 'x':
options |= RegexOptions.ExplicitCapture;
break;
}
}
Regex regex = (Regex)value;
return new Regex(patternText, options);
}
private Regex ReadRegexObject(JsonReader reader, JsonSerializer serializer)
{
string pattern = null;
RegexOptions? options = null;
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string propertyName = reader.Value.ToString();
if (!reader.Read())
throw JsonSerializationException.Create(reader, "Unexpected end when reading Regex.");
if (string.Equals(propertyName, PatternName, StringComparison.OrdinalIgnoreCase))
pattern = (string)reader.Value;
else if (string.Equals(propertyName, OptionsName, StringComparison.OrdinalIgnoreCase))
options = serializer.Deserialize<RegexOptions>(reader);
BsonWriter bsonWriter = writer as BsonWriter;
if (bsonWriter != null)
WriteBson(bsonWriter, regex);
else
reader.Skip();
break;
case JsonToken.Comment:
break;
case JsonToken.EndObject:
if (pattern == null)
throw JsonSerializationException.Create(reader, "Error deserializing Regex. No pattern found.");
return new Regex(pattern, options ?? RegexOptions.None);
WriteJson(writer, regex, serializer);
}
}
throw JsonSerializationException.Create(reader, "Unexpected end when reading Regex.");
}
private bool HasFlag(RegexOptions options, RegexOptions flag)
{
return ((options & flag) == flag);
}
/// <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)
{
return (objectType == typeof (Regex));
private void WriteBson(BsonWriter writer, Regex regex)
{
// Regular expression - The first cstring is the regex pattern, the second
// is the regex options string. Options are identified by characters, which
// must be stored in alphabetical order. Valid options are 'i' for case
// insensitive matching, 'm' for multiline matching, 'x' for verbose mode,
// 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode
// ('.' matches everything), and 'u' to make \w, \W, etc. match unicode.
string options = null;
if (HasFlag(regex.Options, RegexOptions.IgnoreCase))
options += "i";
if (HasFlag(regex.Options, RegexOptions.Multiline))
options += "m";
if (HasFlag(regex.Options, RegexOptions.Singleline))
options += "s";
options += "u";
if (HasFlag(regex.Options, RegexOptions.ExplicitCapture))
options += "x";
writer.WriteRegex(regex.ToString(), options);
}
private void WriteJson(JsonWriter writer, Regex regex, JsonSerializer serializer)
{
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(PatternName) : PatternName);
writer.WriteValue(regex.ToString());
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(OptionsName) : OptionsName);
serializer.Serialize(writer, regex.Options);
writer.WriteEndObject();
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartObject)
return ReadRegexObject(reader, serializer);
if (reader.TokenType == JsonToken.String)
return ReadRegexString(reader);
throw JsonSerializationException.Create(reader, "Unexpected token when reading Regex.");
}
private object ReadRegexString(JsonReader reader)
{
string regexText = (string)reader.Value;
int patternOptionDelimiterIndex = regexText.LastIndexOf('/');
string patternText = regexText.Substring(1, patternOptionDelimiterIndex - 1);
string optionsText = regexText.Substring(patternOptionDelimiterIndex + 1);
RegexOptions options = RegexOptions.None;
foreach (char c in optionsText)
{
switch (c)
{
case 'i':
options |= RegexOptions.IgnoreCase;
break;
case 'm':
options |= RegexOptions.Multiline;
break;
case 's':
options |= RegexOptions.Singleline;
break;
case 'x':
options |= RegexOptions.ExplicitCapture;
break;
}
}
return new Regex(patternText, options);
}
private Regex ReadRegexObject(JsonReader reader, JsonSerializer serializer)
{
string pattern = null;
RegexOptions? options = null;
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string propertyName = reader.Value.ToString();
if (!reader.Read())
throw JsonSerializationException.Create(reader, "Unexpected end when reading Regex.");
if (string.Equals(propertyName, PatternName, StringComparison.OrdinalIgnoreCase))
pattern = (string)reader.Value;
else if (string.Equals(propertyName, OptionsName, StringComparison.OrdinalIgnoreCase))
options = serializer.Deserialize<RegexOptions>(reader);
else
reader.Skip();
break;
case JsonToken.Comment:
break;
case JsonToken.EndObject:
if (pattern == null)
throw JsonSerializationException.Create(reader, "Error deserializing Regex. No pattern found.");
return new Regex(pattern, options ?? RegexOptions.None);
}
}
throw JsonSerializationException.Create(reader, "Unexpected end when reading Regex.");
}
/// <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)
{
return (objectType == typeof(Regex));
}
}
}
}
@@ -33,203 +33,204 @@ using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts an <see cref="Enum"/> to and from its name string value.
/// </summary>
public class StringEnumConverter : JsonConverter
{
private readonly Dictionary<Type, BidirectionalDictionary<string, string>> _enumMemberNamesPerType = new Dictionary<Type, BidirectionalDictionary<string, string>>();
/// <summary>
/// Gets or sets a value indicating whether the written enum text should be camel case.
/// Converts an <see cref="Enum"/> to and from its name string value.
/// </summary>
/// <value><c>true</c> if the written enum text will be camel case; otherwise, <c>false</c>.</value>
public bool CamelCaseText { get; set; }
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public class StringEnumConverter : JsonConverter
{
if (value == null)
{
writer.WriteNull();
return;
}
private readonly Dictionary<Type, BidirectionalDictionary<string, string>> _enumMemberNamesPerType = new Dictionary<Type, BidirectionalDictionary<string, string>>();
Enum e = (Enum)value;
/// <summary>
/// Gets or sets a value indicating whether the written enum text should be camel case.
/// </summary>
/// <value><c>true</c> if the written enum text will be camel case; otherwise, <c>false</c>.</value>
public bool CamelCaseText { get; set; }
string enumName = e.ToString("G");
if (char.IsNumber(enumName[0]) || enumName[0] == '-')
{
// enum value has no name so write number
writer.WriteValue(value);
}
else
{
BidirectionalDictionary<string, string> map = GetEnumNameMap(e.GetType());
string[] names = enumName.Split(',');
for (int i = 0; i < names.Length; i++)
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
string name = names[i].Trim();
string resolvedEnumName;
map.TryGetByFirst(name, out resolvedEnumName);
resolvedEnumName = resolvedEnumName ?? name;
if (CamelCaseText)
resolvedEnumName = StringUtils.ToCamelCase(resolvedEnumName);
names[i] = resolvedEnumName;
}
string finalName = string.Join(", ", names);
writer.WriteValue(finalName);
}
}
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
bool isNullable = ReflectionUtils.IsNullableType(objectType);
Type t = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType;
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullableType(objectType))
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
return null;
}
try
{
if (reader.TokenType == JsonToken.String)
{
string enumText = reader.Value.ToString();
if (enumText == string.Empty && isNullable)
return null;
string finalEnumText;
BidirectionalDictionary<string, string> map = GetEnumNameMap(t);
if (enumText.IndexOf(',') != -1)
{
string[] names = enumText.Split(',');
for (int i = 0; i < names.Length; i++)
if (value == null)
{
string name = names[i].Trim();
names[i] = ResolvedEnumName(map, name);
writer.WriteNull();
return;
}
finalEnumText = string.Join(", ", names);
}
else
{
finalEnumText = ResolvedEnumName(map, enumText);
}
Enum e = (Enum)value;
return Enum.Parse(t, finalEnumText, true);
string enumName = e.ToString("G");
if (char.IsNumber(enumName[0]) || enumName[0] == '-')
{
// enum value has no name so write number
writer.WriteValue(value);
}
else
{
BidirectionalDictionary<string, string> map = GetEnumNameMap(e.GetType());
string[] names = enumName.Split(',');
for (int i = 0; i < names.Length; i++)
{
string name = names[i].Trim();
string resolvedEnumName;
map.TryGetByFirst(name, out resolvedEnumName);
resolvedEnumName = resolvedEnumName ?? name;
if (CamelCaseText)
resolvedEnumName = StringUtils.ToCamelCase(resolvedEnumName);
names[i] = resolvedEnumName;
}
string finalName = string.Join(", ", names);
writer.WriteValue(finalName);
}
}
if (reader.TokenType == JsonToken.Integer)
return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t);
}
catch (Exception ex)
{
throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.FormatValueForPrint(reader.Value), objectType), ex);
}
throw JsonSerializationException.Create(reader, "Unexpected token when parsing enum. Expected String or Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
private static string ResolvedEnumName(BidirectionalDictionary<string, string> map, string enumText)
{
string resolvedEnumName;
map.TryGetBySecond(enumText, out resolvedEnumName);
resolvedEnumName = resolvedEnumName ?? enumText;
return resolvedEnumName;
}
private BidirectionalDictionary<string, string> GetEnumNameMap(Type t)
{
BidirectionalDictionary<string, string> map;
if (!_enumMemberNamesPerType.TryGetValue(t, out map))
{
lock (_enumMemberNamesPerType)
/// <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>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (_enumMemberNamesPerType.TryGetValue(t, out map))
return map;
bool isNullable = ReflectionUtils.IsNullableType(objectType);
Type t = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType;
map = new BidirectionalDictionary<string, string>(
StringComparer.OrdinalIgnoreCase,
StringComparer.OrdinalIgnoreCase);
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullableType(objectType))
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
return null;
}
try
{
if (reader.TokenType == JsonToken.String)
{
string enumText = reader.Value.ToString();
if (enumText == string.Empty && isNullable)
return null;
string finalEnumText;
BidirectionalDictionary<string, string> map = GetEnumNameMap(t);
if (enumText.IndexOf(',') != -1)
{
string[] names = enumText.Split(',');
for (int i = 0; i < names.Length; i++)
{
string name = names[i].Trim();
names[i] = ResolvedEnumName(map, name);
}
finalEnumText = string.Join(", ", names);
}
else
{
finalEnumText = ResolvedEnumName(map, enumText);
}
return Enum.Parse(t, finalEnumText, true);
}
if (reader.TokenType == JsonToken.Integer)
return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t);
}
catch (Exception ex)
{
throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.FormatValueForPrint(reader.Value), objectType), ex);
}
throw JsonSerializationException.Create(reader, "Unexpected token when parsing enum. Expected String or Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
private static string ResolvedEnumName(BidirectionalDictionary<string, string> map, string enumText)
{
string resolvedEnumName;
map.TryGetBySecond(enumText, out resolvedEnumName);
resolvedEnumName = resolvedEnumName ?? enumText;
return resolvedEnumName;
}
private BidirectionalDictionary<string, string> GetEnumNameMap(Type t)
{
BidirectionalDictionary<string, string> map;
if (!_enumMemberNamesPerType.TryGetValue(t, out map))
{
lock (_enumMemberNamesPerType)
{
if (_enumMemberNamesPerType.TryGetValue(t, out map))
return map;
map = new BidirectionalDictionary<string, string>(
StringComparer.OrdinalIgnoreCase,
StringComparer.OrdinalIgnoreCase);
foreach (FieldInfo f in t.GetFields())
{
string n1 = f.Name;
string n2;
foreach (FieldInfo f in t.GetFields())
{
string n1 = f.Name;
string n2;
#if !NET20
n2 = f.GetCustomAttributes(typeof (EnumMemberAttribute), true)
.Cast<EnumMemberAttribute>()
.Select(a => a.Value)
.SingleOrDefault() ?? f.Name;
n2 = f.GetCustomAttributes(typeof(EnumMemberAttribute), true)
.Cast<EnumMemberAttribute>()
.Select(a => a.Value)
.SingleOrDefault() ?? f.Name;
#else
n2 = f.Name;
#endif
string s;
if (map.TryGetBySecond(n2, out s))
{
throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'."
.FormatWith(CultureInfo.InvariantCulture, n2, t.Name));
string s;
if (map.TryGetBySecond(n2, out s))
{
throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'."
.FormatWith(CultureInfo.InvariantCulture, n2, t.Name));
}
map.Set(n1, n2);
}
_enumMemberNamesPerType[t] = map;
}
}
map.Set(n1, n2);
}
_enumMemberNamesPerType[t] = map;
return map;
}
}
return map;
/// <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();
}
}
/// <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();
}
}
}
@@ -29,78 +29,78 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="Version"/> to and from a string (e.g. "1.2.3.4").
/// </summary>
public class VersionConverter : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// Converts a <see cref="Version"/> to and from a string (e.g. "1.2.3.4").
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public class VersionConverter : JsonConverter
{
if (value == null)
{
writer.WriteNull();
}
else if (value is Version)
{
writer.WriteValue(value.ToString());
}
else
{
throw new JsonSerializationException("Expected Version object value");
}
}
/// <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>
/// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
else
{
if (reader.TokenType == JsonToken.String)
/// <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>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
try
{
Version v = new Version((string) reader.Value);
return v;
}
catch (Exception ex)
{
throw JsonSerializationException.Create(reader, "Error parsing version string: {0}".FormatWith(CultureInfo.InvariantCulture, reader.Value), ex);
}
if (value == null)
{
writer.WriteNull();
}
else if (value is Version)
{
writer.WriteValue(value.ToString());
}
else
{
throw new JsonSerializationException("Expected Version object value");
}
}
else
{
throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing version. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
}
}
}
/// <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)
{
return objectType == typeof (Version);
/// <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>
/// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
else
{
if (reader.TokenType == JsonToken.String)
{
try
{
Version v = new Version((string)reader.Value);
return v;
}
catch (Exception ex)
{
throw JsonSerializationException.Create(reader, "Error parsing version string: {0}".FormatWith(CultureInfo.InvariantCulture, reader.Value), ex);
}
}
else
{
throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing version. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
}
}
}
/// <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)
{
return objectType == typeof(Version);
}
}
}
}
File diff suppressed because it is too large Load Diff