-Fixed EntityKeyMemberConverter not using property name resolve

-Added DiscriminatedUnionConverter
This commit is contained in:
James Newton-King
2013-12-01 21:53:14 +13:00
parent cd0bc9591d
commit ea87bafc42
9 changed files with 934 additions and 115 deletions
@@ -0,0 +1,215 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Odbc;
using System.Reflection;
using Newtonsoft.Json.Serialization;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a F# discriminated union type to and from JSON.
/// </summary>
public class DiscriminatedUnionConverter : JsonConverter
{
private static bool _initialized;
private static MethodCall<object, object> _isUnion;
private static MethodCall<object, object> _getUnionFields;
private static MethodCall<object, object> _getUnionCases;
private static MethodCall<object, object> _makeUnion;
private static Func<object, object> _getUnionCaseInfoName;
private static Func<object, object> _getUnionCaseInfo;
private static Func<object, object> _getUnionCaseFields;
private static MethodCall<object, object> _getUnionCaseInfoFields;
private const string CasePropertyName = "Case";
private const string FieldsPropertyName = "Fields";
/// <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)
{
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
Type t = value.GetType();
object result = _getUnionFields(null, value, t, null);
object info = _getUnionCaseInfo(result);
object fields = _getUnionCaseFields(result);
object caseName = _getUnionCaseInfoName(info);
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(CasePropertyName) : CasePropertyName);
writer.WriteValue((string)caseName);
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(FieldsPropertyName) : FieldsPropertyName);
serializer.Serialize(writer, fields);
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.Null)
return null;
IEnumerable cases = (IEnumerable)_getUnionCases(null, objectType, null);
ReadAndAssertProperty(reader, CasePropertyName);
ReadAndAssert(reader);
string caseName = reader.Value.ToString();
object matchingCaseInfo = null;
foreach (object c in cases)
{
if ((string)_getUnionCaseInfoName(c) == caseName)
{
matchingCaseInfo = c;
break;
}
}
if (matchingCaseInfo == null)
throw new JsonSerializationException("No union type found with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
ReadAndAssertProperty(reader, FieldsPropertyName);
// start array
ReadAndAssert(reader);
// first value
ReadAndAssert(reader);
PropertyInfo[] fieldProperties = (PropertyInfo[])_getUnionCaseInfoFields(matchingCaseInfo);
List<object> fieldValues = new List<object>();
foreach (PropertyInfo field in fieldProperties)
{
fieldValues.Add(serializer.Deserialize(reader, field.PropertyType));
ReadAndAssert(reader);
}
// end object
ReadAndAssert(reader);
return _makeUnion(null, matchingCaseInfo, fieldValues.ToArray(), null);
}
/// <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 (typeof(IEnumerable).IsAssignableFrom(objectType))
return false;
// all fsharp objects have CompilationMappingAttribute
// get the fsharp assembly from the attribute and initialize latebound methods
object[] attributes = objectType.GetCustomAttributes(true);
bool isFSharpType = false;
foreach (object attribute in attributes)
{
Type attributeType = attribute.GetType();
if (attributeType.Name == "CompilationMappingAttribute")
{
EnsureInitialized(attributeType);
isFSharpType = true;
break;
}
}
if (!isFSharpType)
return false;
return (bool)_isUnion(null, objectType, null);
}
private static void EnsureInitialized(Type attributeType)
{
if (!_initialized)
{
_initialized = true;
Assembly fsharpCoreAssembly = attributeType.Assembly;
Type fsharpType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpType");
MethodInfo isUnionMethodInfo = fsharpType.GetMethod("IsUnion", BindingFlags.Public | BindingFlags.Static);
_isUnion = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(isUnionMethodInfo);
MethodInfo getUnionCasesMethodInfo = fsharpType.GetMethod("GetUnionCases", BindingFlags.Public | BindingFlags.Static);
_getUnionCases = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(getUnionCasesMethodInfo);
Type fsharpValue = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpValue");
MethodInfo getUnionFieldsMethodInfo = fsharpValue.GetMethod("GetUnionFields", BindingFlags.Public | BindingFlags.Static);
_getUnionFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(getUnionFieldsMethodInfo);
_getUnionCaseInfo = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(getUnionFieldsMethodInfo.ReturnType.GetProperty("Item1"));
_getUnionCaseFields = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(getUnionFieldsMethodInfo.ReturnType.GetProperty("Item2"));
MethodInfo makeUnionMethodInfo = fsharpValue.GetMethod("MakeUnion", BindingFlags.Public | BindingFlags.Static);
_makeUnion = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(makeUnionMethodInfo);
Type unionCaseInfo = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.UnionCaseInfo");
_getUnionCaseInfoName = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(unionCaseInfo.GetProperty("Name"));
_getUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(unionCaseInfo.GetMethod("GetFields"));
}
}
private static void ReadAndAssertProperty(JsonReader reader, string propertyName)
{
ReadAndAssert(reader);
if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value.ToString(), propertyName, StringComparison.OrdinalIgnoreCase))
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.");
}
}
}
@@ -0,0 +1,215 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Odbc;
using System.Reflection;
using Newtonsoft.Json.Serialization;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a F# union type to and from JSON.
/// </summary>
public class DiscriminatedUnionTypeConverter : JsonConverter
{
private static bool _initialized;
private static MethodCall<object, object> _isUnion;
private static MethodCall<object, object> _getUnionFields;
private static MethodCall<object, object> _getUnionCases;
private static MethodCall<object, object> _makeUnion;
private static Func<object, object> _getUnionCaseInfoName;
private static Func<object, object> _getUnionCaseInfo;
private static Func<object, object> _getUnionCaseFields;
private static MethodCall<object, object> _getUnionCaseInfoFields;
private const string CasePropertyName = "Case";
private const string FieldsPropertyName = "Fields";
/// <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)
{
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
Type t = value.GetType();
object result = _getUnionFields(null, value, t, null);
object info = _getUnionCaseInfo(result);
object fields = _getUnionCaseFields(result);
object caseName = _getUnionCaseInfoName(info);
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(CasePropertyName) : CasePropertyName);
writer.WriteValue((string)caseName);
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(FieldsPropertyName) : FieldsPropertyName);
serializer.Serialize(writer, fields);
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.Null)
return null;
IEnumerable cases = (IEnumerable)_getUnionCases(null, objectType, null);
ReadAndAssertProperty(reader, CasePropertyName);
ReadAndAssert(reader);
string caseName = reader.Value.ToString();
object matchingCaseInfo = null;
foreach (object c in cases)
{
if ((string)_getUnionCaseInfoName(c) == caseName)
{
matchingCaseInfo = c;
break;
}
}
if (matchingCaseInfo == null)
throw new JsonSerializationException("No union type found with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
ReadAndAssertProperty(reader, FieldsPropertyName);
// start array
ReadAndAssert(reader);
// first value
ReadAndAssert(reader);
PropertyInfo[] fieldProperties = (PropertyInfo[])_getUnionCaseInfoFields(matchingCaseInfo);
List<object> fieldValues = new List<object>();
foreach (PropertyInfo field in fieldProperties)
{
fieldValues.Add(serializer.Deserialize(reader, field.PropertyType));
ReadAndAssert(reader);
}
// end object
ReadAndAssert(reader);
return _makeUnion(null, matchingCaseInfo, fieldValues.ToArray(), null);
}
/// <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 (typeof(IEnumerable).IsAssignableFrom(objectType))
return false;
// all fsharp objects have CompilationMappingAttribute
// get the fsharp assembly from the attribute and initialize latebound methods
object[] attributes = objectType.GetCustomAttributes(true);
bool isFSharpType = false;
foreach (object attribute in attributes)
{
Type attributeType = attribute.GetType();
if (attributeType.Name == "CompilationMappingAttribute")
{
EnsureInitialized(attributeType);
isFSharpType = true;
break;
}
}
if (!isFSharpType)
return false;
return (bool)_isUnion(null, objectType, null);
}
private static void EnsureInitialized(Type attributeType)
{
if (!_initialized)
{
_initialized = true;
Assembly fsharpCoreAssembly = attributeType.Assembly;
Type fsharpType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpType");
MethodInfo isUnionMethodInfo = fsharpType.GetMethod("IsUnion", BindingFlags.Public | BindingFlags.Static);
_isUnion = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(isUnionMethodInfo);
MethodInfo getUnionCasesMethodInfo = fsharpType.GetMethod("GetUnionCases", BindingFlags.Public | BindingFlags.Static);
_getUnionCases = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(getUnionCasesMethodInfo);
Type fsharpValue = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpValue");
MethodInfo getUnionFieldsMethodInfo = fsharpValue.GetMethod("GetUnionFields", BindingFlags.Public | BindingFlags.Static);
_getUnionFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(getUnionFieldsMethodInfo);
_getUnionCaseInfo = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(getUnionFieldsMethodInfo.ReturnType.GetProperty("Item1"));
_getUnionCaseFields = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(getUnionFieldsMethodInfo.ReturnType.GetProperty("Item2"));
MethodInfo makeUnionMethodInfo = fsharpValue.GetMethod("MakeUnion", BindingFlags.Public | BindingFlags.Static);
_makeUnion = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(makeUnionMethodInfo);
Type unionCaseInfo = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.UnionCaseInfo");
_getUnionCaseInfoName = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(unionCaseInfo.GetProperty("Name"));
_getUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(unionCaseInfo.GetMethod("GetFields"));
}
}
private static void ReadAndAssertProperty(JsonReader reader, string propertyName)
{
ReadAndAssert(reader);
if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value.ToString(), propertyName, StringComparison.OrdinalIgnoreCase))
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.");
}
}
}
@@ -44,6 +44,10 @@ namespace Newtonsoft.Json.Converters
{
private const string EntityKeyMemberFullTypeName = "System.Data.EntityKeyMember";
private const string KeyPropertyName = "Key";
private const string TypePropertyName = "Type";
private const string ValuePropertyName = "Value";
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
@@ -52,16 +56,18 @@ namespace Newtonsoft.Json.Converters
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
IEntityKeyMember entityKeyMember = DynamicWrapper.CreateWrapper<IEntityKeyMember>(value);
Type keyType = (entityKeyMember.Value != null) ? entityKeyMember.Value.GetType() : null;
writer.WriteStartObject();
writer.WritePropertyName("Key");
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyPropertyName) : KeyPropertyName);
writer.WriteValue(entityKeyMember.Key);
writer.WritePropertyName("Type");
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(TypePropertyName) : TypePropertyName);
writer.WriteValue((keyType != null) ? keyType.FullName : null);
writer.WritePropertyName("Value");
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(ValuePropertyName) : ValuePropertyName);
if (keyType != null)
{
@@ -83,7 +89,7 @@ namespace Newtonsoft.Json.Converters
{
ReadAndAssert(reader);
if (reader.TokenType != JsonToken.PropertyName || reader.Value.ToString() != propertyName)
if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value.ToString(), propertyName, StringComparison.OrdinalIgnoreCase))
throw new JsonSerializationException("Expected JSON property '{0}'.".FormatWith(CultureInfo.InvariantCulture, propertyName));
}
@@ -105,17 +111,17 @@ namespace Newtonsoft.Json.Converters
{
IEntityKeyMember entityKeyMember = DynamicWrapper.CreateWrapper<IEntityKeyMember>(Activator.CreateInstance(objectType));
ReadAndAssertProperty(reader, "Key");
ReadAndAssertProperty(reader, KeyPropertyName);
ReadAndAssert(reader);
entityKeyMember.Key = reader.Value.ToString();
ReadAndAssertProperty(reader, "Type");
ReadAndAssertProperty(reader, TypePropertyName);
ReadAndAssert(reader);
string type = reader.Value.ToString();
Type t = Type.GetType(type);
ReadAndAssertProperty(reader, "Value");
ReadAndAssertProperty(reader, ValuePropertyName);
ReadAndAssert(reader);
entityKeyMember.Value = serializer.Deserialize(reader, t);
@@ -133,9 +139,8 @@ namespace Newtonsoft.Json.Converters
/// </returns>
public override bool CanConvert(Type objectType)
{
return (objectType.AssignableToTypeName(EntityKeyMemberFullTypeName));
return objectType.AssignableToTypeName(EntityKeyMemberFullTypeName);
}
}
}
#endif
@@ -0,0 +1,215 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Odbc;
using System.Reflection;
using Newtonsoft.Json.Serialization;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a F# union type to and from JSON.
/// </summary>
public class UnionTypeConverter : JsonConverter
{
private static bool _initialized;
private static MethodCall<object, object> _isUnionMethod;
private static MethodCall<object, object> _getUnionFieldsMethod;
private static MethodCall<object, object> _getUnionCasesMethod;
private static MethodCall<object, object> _makeUnionMethod;
private static Func<object, object> _getUnionCaseInfoName;
private static Func<object, object> _getUnionCaseInfo;
private static Func<object, object> _getUnionCaseFields;
private static MethodCall<object, object> _getUnionCaseInfoFields;
private const string CasePropertyName = "Case";
private const string FieldsPropertyName = "Fields";
/// <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)
{
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
Type t = value.GetType();
object result = _getUnionFieldsMethod(null, value, t, null);
object info = _getUnionCaseInfo(result);
object fields = _getUnionCaseFields(result);
object caseName = _getUnionCaseInfoName(info);
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(CasePropertyName) : CasePropertyName);
writer.WriteValue((string)caseName);
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(FieldsPropertyName) : FieldsPropertyName);
serializer.Serialize(writer, fields);
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.Null)
return null;
IEnumerable cases = (IEnumerable)_getUnionCasesMethod(null, objectType, null);
ReadAndAssertProperty(reader, CasePropertyName);
ReadAndAssert(reader);
string caseName = reader.Value.ToString();
object matchingCaseInfo = null;
foreach (object c in cases)
{
if ((string)_getUnionCaseInfoName(c) == caseName)
{
matchingCaseInfo = c;
break;
}
}
if (matchingCaseInfo == null)
throw new JsonSerializationException("No union type found with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
ReadAndAssertProperty(reader, FieldsPropertyName);
// start array
ReadAndAssert(reader);
// first value
ReadAndAssert(reader);
PropertyInfo[] fieldProperties = (PropertyInfo[])_getUnionCaseInfoFields(matchingCaseInfo);
List<object> fieldValues = new List<object>();
foreach (PropertyInfo field in fieldProperties)
{
fieldValues.Add(serializer.Deserialize(reader, field.PropertyType));
ReadAndAssert(reader);
}
// end object
ReadAndAssert(reader);
return _makeUnionMethod(null, matchingCaseInfo, fieldValues.ToArray(), null);
}
/// <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 (typeof(IEnumerable).IsAssignableFrom(objectType))
return false;
// all fsharp objects have CompilationMappingAttribute
// get the fsharp assembly from the attribute and initialize latebound methods
object[] attributes = objectType.GetCustomAttributes(true);
bool isFSharpType = false;
foreach (object attribute in attributes)
{
Type attributeType = attribute.GetType();
if (attributeType.Name == "CompilationMappingAttribute")
{
EnsureInitialized(attributeType);
isFSharpType = true;
break;
}
}
if (!isFSharpType)
return false;
return (bool)_isUnionMethod(null, objectType, null);
}
private static void EnsureInitialized(Type attributeType)
{
if (!_initialized)
{
_initialized = true;
Assembly fsharpCoreAssembly = attributeType.Assembly;
Type fsharpType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpType");
MethodInfo isUnionMethodInfo = fsharpType.GetMethod("IsUnion", BindingFlags.Public | BindingFlags.Static);
_isUnionMethod = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(isUnionMethodInfo);
MethodInfo getUnionCasesMethodInfo = fsharpType.GetMethod("GetUnionCases", BindingFlags.Public | BindingFlags.Static);
_getUnionCasesMethod = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(getUnionCasesMethodInfo);
Type fsharpValue = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpValue");
MethodInfo getUnionFieldsMethodInfo = fsharpValue.GetMethod("GetUnionFields", BindingFlags.Public | BindingFlags.Static);
_getUnionFieldsMethod = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(getUnionFieldsMethodInfo);
_getUnionCaseInfo = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(getUnionFieldsMethodInfo.ReturnType.GetProperty("Item1"));
_getUnionCaseFields = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(getUnionFieldsMethodInfo.ReturnType.GetProperty("Item2"));
MethodInfo makeUnionMethodInfo = fsharpValue.GetMethod("MakeUnion", BindingFlags.Public | BindingFlags.Static);
_makeUnionMethod = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(makeUnionMethodInfo);
Type unionCaseInfo = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.UnionCaseInfo");
_getUnionCaseInfoName = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(unionCaseInfo.GetProperty("Name"));
_getUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(unionCaseInfo.GetMethod("GetFields"));
}
}
private static void ReadAndAssertProperty(JsonReader reader, string propertyName)
{
ReadAndAssert(reader);
if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value.ToString(), propertyName, StringComparison.OrdinalIgnoreCase))
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.");
}
}
}
@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
namespace Newtonsoft.Json.Linq.JsonPath
{
internal enum QueryOperator
{
None,
Equals,
NotEquals,
Exists,
LessThan,
LessThanOrEquals,
GreaterThan,
GreaterThanOrEquals,
And,
Or
}
internal abstract class QueryExpression
{
public QueryOperator Operator { get; set; }
public abstract bool IsMatch(JToken t);
}
internal class CompositeExpression : QueryExpression
{
public List<QueryExpression> Expressions { get; set; }
public CompositeExpression()
{
Expressions = new List<QueryExpression>();
}
public override bool IsMatch(JToken t)
{
switch (Operator)
{
case QueryOperator.And:
foreach (QueryExpression e in Expressions)
{
if (!e.IsMatch(t))
return false;
}
return true;
case QueryOperator.Or:
foreach (QueryExpression e in Expressions)
{
if (e.IsMatch(t))
return true;
}
return false;
default:
throw new ArgumentOutOfRangeException();
}
}
}
internal class BooleanQueryExpression : QueryExpression
{
public List<PathFilter> Path { get; set; }
public JValue Value { get; set; }
public override bool IsMatch(JToken t)
{
IEnumerable<JToken> pathResult = JPath.Evaluate(Path, t, false);
foreach (JToken r in pathResult)
{
JValue v = r as JValue;
switch (Operator)
{
case QueryOperator.Equals:
if (v != null && v.Equals(Value))
return true;
break;
case QueryOperator.NotEquals:
if (v != null && !v.Equals(Value))
return true;
break;
case QueryOperator.GreaterThan:
if (v != null && v.CompareTo(Value) > 0)
return true;
break;
case QueryOperator.GreaterThanOrEquals:
if (v != null && v.CompareTo(Value) >= 0)
return true;
break;
case QueryOperator.LessThan:
if (v != null && v.CompareTo(Value) < 0)
return true;
break;
case QueryOperator.LessThanOrEquals:
if (v != null && v.CompareTo(Value) <= 0)
return true;
break;
case QueryOperator.Exists:
return true;
default:
throw new ArgumentOutOfRangeException();
}
}
return false;
}
}
}
@@ -4,109 +4,6 @@ using System.Linq;
namespace Newtonsoft.Json.Linq.JsonPath
{
internal enum QueryOperator
{
None,
Equals,
NotEquals,
Exists,
LessThan,
LessThanOrEquals,
GreaterThan,
GreaterThanOrEquals,
And,
Or
}
internal abstract class QueryExpression
{
public QueryOperator Operator { get; set; }
public abstract bool IsMatch(JToken t);
}
internal class CompositeExpression : QueryExpression
{
public List<QueryExpression> Expressions { get; set; }
public CompositeExpression()
{
Expressions = new List<QueryExpression>();
}
public override bool IsMatch(JToken t)
{
switch (Operator)
{
case QueryOperator.And:
foreach (QueryExpression e in Expressions)
{
if (!e.IsMatch(t))
return false;
}
return true;
case QueryOperator.Or:
foreach (QueryExpression e in Expressions)
{
if (e.IsMatch(t))
return true;
}
return false;
default:
throw new ArgumentOutOfRangeException();
}
}
}
internal class BooleanQueryExpression : QueryExpression
{
public List<PathFilter> Path { get; set; }
public JValue Value { get; set; }
public override bool IsMatch(JToken t)
{
IEnumerable<JToken> pathResult = JPath.Evaluate(Path, t, false);
foreach (JToken r in pathResult)
{
JValue v = r as JValue;
switch (Operator)
{
case QueryOperator.Equals:
if (v != null && v.Equals(Value))
return true;
break;
case QueryOperator.NotEquals:
if (v != null && !v.Equals(Value))
return true;
break;
case QueryOperator.GreaterThan:
if (v != null && v.CompareTo(Value) > 0)
return true;
break;
case QueryOperator.GreaterThanOrEquals:
if (v != null && v.CompareTo(Value) >= 0)
return true;
break;
case QueryOperator.LessThan:
if (v != null && v.CompareTo(Value) < 0)
return true;
break;
case QueryOperator.LessThanOrEquals:
if (v != null && v.CompareTo(Value) <= 0)
return true;
break;
case QueryOperator.Exists:
return true;
default:
throw new ArgumentOutOfRangeException();
}
}
return false;
}
}
internal class QueryFilter : PathFilter
{
public QueryExpression Expression { get; set; }
@@ -60,6 +60,7 @@
<Compile Include="Converters\DataSetConverter.cs" />
<Compile Include="Converters\DataTableConverter.cs" />
<Compile Include="Converters\DateTimeConverterBase.cs" />
<Compile Include="Converters\DiscriminatedUnionConverter.cs" />
<Compile Include="Converters\EntityKeyMemberConverter.cs" />
<Compile Include="Converters\ExpandoObjectConverter.cs" />
<Compile Include="Converters\IsoDateTimeConverter.cs" />
@@ -121,6 +122,7 @@
<Compile Include="Linq\JPropertyKeyedCollection.cs" />
<Compile Include="Linq\JRaw.cs" />
<Compile Include="Linq\JsonPath\PathFilter.cs" />
<Compile Include="Linq\JsonPath\QueryExpression.cs" />
<Compile Include="Linq\JsonPath\QueryFilter.cs" />
<Compile Include="Linq\JsonPath\ScanFilter.cs" />
<Compile Include="Linq\JToken.cs" />
@@ -103,7 +103,7 @@ namespace Newtonsoft.Json.Serialization
#if !(NET35 || NET20 || PORTABLE40)
new ExpandoObjectConverter(),
#endif
#if (!(PORTABLE40))
#if !(PORTABLE40)
new XmlNodeConverter(),
#endif
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
@@ -112,11 +112,12 @@ namespace Newtonsoft.Json.Serialization
new DataTableConverter(),
#endif
#if NETFX_CORE
new JsonValueConverter(),
new JsonValueConverter(),
#endif
new KeyValuePairConverter(),
new BsonObjectIdConverter(),
new RegexConverter()
new RegexConverter(),
new DiscriminatedUnionConverter()
};
private static Dictionary<ResolverContractKey, JsonContract> _sharedContractCache;