chore: 初始化北汽福田MES采集程序

This commit is contained in:
yexingqiang
2026-05-29 13:44:10 +08:00
commit c5e248e993
1399 changed files with 187196 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
#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.Reflection;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization
{
internal static class CachedAttributeGetter<T> where T : Attribute
{
private static readonly ThreadSafeStore<object, T> TypeAttributeCache = new ThreadSafeStore<object, T>(JsonTypeReflector.GetAttribute<T>);
public static T GetAttribute(object type)
{
return TypeAttributeCache.Get(type);
}
}
}

View File

@@ -0,0 +1,57 @@
#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.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Resolves member mappings for a type, camel casing property names.
/// </summary>
public class CamelCasePropertyNamesContractResolver : DefaultContractResolver
{
/// <summary>
/// Initializes a new instance of the <see cref="CamelCasePropertyNamesContractResolver"/> class.
/// </summary>
public CamelCasePropertyNamesContractResolver()
#pragma warning disable 612,618
: base(true)
#pragma warning restore 612,618
{
}
/// <summary>
/// Resolves the name of the property.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <returns>The property name camel cased.</returns>
protected override string ResolvePropertyName(string propertyName)
{
// lower case the first letter (or more) of the passed in name
return StringUtils.ToCamelCase(propertyName);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,89 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Serialization
{
internal class DefaultReferenceResolver : IReferenceResolver
{
private int _referenceCount;
private BidirectionalDictionary<string, object> GetMappings(object context)
{
JsonSerializerInternalBase internalSerializer;
if (context is JsonSerializerInternalBase)
{
internalSerializer = (JsonSerializerInternalBase)context;
}
else if (context is JsonSerializerProxy)
{
internalSerializer = ((JsonSerializerProxy)context).GetInternalSerializer();
}
else
{
throw new JsonException("The DefaultReferenceResolver can only be used internally.");
}
return internalSerializer.DefaultReferenceMappings;
}
public object ResolveReference(object context, string reference)
{
object value;
GetMappings(context).TryGetByFirst(reference, out value);
return value;
}
public string GetReference(object context, object value)
{
var mappings = GetMappings(context);
string reference;
if (!mappings.TryGetBySecond(value, out reference))
{
_referenceCount++;
reference = _referenceCount.ToString(CultureInfo.InvariantCulture);
mappings.Set(reference, value);
}
return reference;
}
public void AddReference(object context, string reference, object value)
{
GetMappings(context).Set(reference, value);
}
public bool IsReferenced(object context, object value)
{
string reference;
return GetMappings(context).TryGetBySecond(value, out reference);
}
}
}

View File

@@ -0,0 +1,164 @@
#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.Runtime.Serialization;
using System.Reflection;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// The default serialization binder used when resolving and loading classes from type names.
/// </summary>
public class DefaultSerializationBinder : SerializationBinder
{
internal static readonly DefaultSerializationBinder Instance = new DefaultSerializationBinder();
private readonly ThreadSafeStore<TypeNameKey, Type> _typeCache = new ThreadSafeStore<TypeNameKey, Type>(GetTypeFromTypeNameKey);
private static Type GetTypeFromTypeNameKey(TypeNameKey typeNameKey)
{
string assemblyName = typeNameKey.AssemblyName;
string typeName = typeNameKey.TypeName;
if (assemblyName != null)
{
Assembly assembly;
#if !(DOTNET || PORTABLE40 || PORTABLE)
// look, I don't like using obsolete methods as much as you do but this is the only way
// Assembly.Load won't check the GAC for a partial name
#pragma warning disable 618,612
assembly = Assembly.LoadWithPartialName(assemblyName);
#pragma warning restore 618,612
#elif DOTNET || PORTABLE
assembly = Assembly.Load(new AssemblyName(assemblyName));
#else
assembly = Assembly.Load(assemblyName);
#endif
#if !(PORTABLE40 || PORTABLE || DOTNET)
if (assembly == null)
{
// will find assemblies loaded with Assembly.LoadFile outside of the main directory
Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly a in loadedAssemblies)
{
if (a.FullName == assemblyName)
{
assembly = a;
break;
}
}
}
#endif
if (assembly == null)
{
throw new JsonSerializationException("Could not load assembly '{0}'.".FormatWith(CultureInfo.InvariantCulture, assemblyName));
}
Type type = assembly.GetType(typeName);
if (type == null)
{
throw new JsonSerializationException("Could not find type '{0}' in assembly '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeName, assembly.FullName));
}
return type;
}
else
{
return Type.GetType(typeName);
}
}
internal struct TypeNameKey : IEquatable<TypeNameKey>
{
internal readonly string AssemblyName;
internal readonly string TypeName;
public TypeNameKey(string assemblyName, string typeName)
{
AssemblyName = assemblyName;
TypeName = typeName;
}
public override int GetHashCode()
{
return ((AssemblyName != null) ? AssemblyName.GetHashCode() : 0)
^ ((TypeName != null) ? TypeName.GetHashCode() : 0);
}
public override bool Equals(object obj)
{
if (!(obj is TypeNameKey))
{
return false;
}
return Equals((TypeNameKey)obj);
}
public bool Equals(TypeNameKey other)
{
return (AssemblyName == other.AssemblyName && TypeName == other.TypeName);
}
}
/// <summary>
/// When overridden in a derived class, controls the binding of a serialized object to a type.
/// </summary>
/// <param name="assemblyName">Specifies the <see cref="T:System.Reflection.Assembly"/> name of the serialized object.</param>
/// <param name="typeName">Specifies the <see cref="T:System.Type"/> name of the serialized object.</param>
/// <returns>
/// The type of the object the formatter creates a new instance of.
/// </returns>
public override Type BindToType(string assemblyName, string typeName)
{
return _typeCache.Get(new TypeNameKey(assemblyName, typeName));
}
#if !(NET35 || NET20)
/// <summary>
/// When overridden in a derived class, controls the binding of a serialized object to a type.
/// </summary>
/// <param name="serializedType">The type of the object the formatter creates a new instance of.</param>
/// <param name="assemblyName">Specifies the <see cref="T:System.Reflection.Assembly"/> name of the serialized object. </param>
/// <param name="typeName">Specifies the <see cref="T:System.Type"/> name of the serialized object. </param>
public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
{
#if (DOTNET || PORTABLE)
assemblyName = serializedType.GetTypeInfo().Assembly.FullName;
typeName = serializedType.FullName;
#else
assemblyName = serializedType.Assembly.FullName;
typeName = serializedType.FullName;
#endif
}
#endif
}
}

View File

@@ -0,0 +1,79 @@
#if !(PORTABLE40 || PORTABLE || DOTNET)
using System;
using System.Diagnostics;
using DiagnosticsTrace = System.Diagnostics.Trace;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Represents a trace writer that writes to the application's <see cref="TraceListener"/> instances.
/// </summary>
public class DiagnosticsTraceWriter : ITraceWriter
{
/// <summary>
/// Gets the <see cref="TraceLevel"/> that will be used to filter the trace messages passed to the writer.
/// For example a filter level of <code>Info</code> will exclude <code>Verbose</code> messages and include <code>Info</code>,
/// <code>Warning</code> and <code>Error</code> messages.
/// </summary>
/// <value>
/// The <see cref="TraceLevel"/> that will be used to filter the trace messages passed to the writer.
/// </value>
public TraceLevel LevelFilter { get; set; }
private TraceEventType GetTraceEventType(TraceLevel level)
{
switch (level)
{
case TraceLevel.Error:
return TraceEventType.Error;
case TraceLevel.Warning:
return TraceEventType.Warning;
case TraceLevel.Info:
return TraceEventType.Information;
case TraceLevel.Verbose:
return TraceEventType.Verbose;
default:
throw new ArgumentOutOfRangeException(nameof(level));
}
}
/// <summary>
/// Writes the specified trace level, message and optional exception.
/// </summary>
/// <param name="level">The <see cref="TraceLevel"/> at which to write this trace.</param>
/// <param name="message">The trace message.</param>
/// <param name="ex">The trace exception. This parameter is optional.</param>
public void Trace(TraceLevel level, string message, Exception ex)
{
if (level == TraceLevel.Off)
{
return;
}
TraceEventCache eventCache = new TraceEventCache();
TraceEventType traceEventType = GetTraceEventType(level);
foreach (TraceListener listener in DiagnosticsTrace.Listeners)
{
if (!listener.IsThreadSafe)
{
lock (listener)
{
listener.TraceEvent(eventCache, "Newtonsoft.Json", traceEventType, 0, message);
}
}
else
{
listener.TraceEvent(eventCache, "Newtonsoft.Json", traceEventType, 0, message);
}
if (DiagnosticsTrace.AutoFlush)
{
listener.Flush();
}
}
}
}
}
#endif

View File

@@ -0,0 +1,120 @@
#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
#if !(PORTABLE40 || PORTABLE || DOTNET)
using System;
using System.Collections.Generic;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#endif
using System.Text;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Get and set values for a <see cref="MemberInfo"/> using dynamic methods.
/// </summary>
public class DynamicValueProvider : IValueProvider
{
private readonly MemberInfo _memberInfo;
private Func<object, object> _getter;
private Action<object, object> _setter;
/// <summary>
/// Initializes a new instance of the <see cref="DynamicValueProvider"/> class.
/// </summary>
/// <param name="memberInfo">The member info.</param>
public DynamicValueProvider(MemberInfo memberInfo)
{
ValidationUtils.ArgumentNotNull(memberInfo, nameof(memberInfo));
_memberInfo = memberInfo;
}
/// <summary>
/// Sets the value.
/// </summary>
/// <param name="target">The target to set the value on.</param>
/// <param name="value">The value to set on the target.</param>
public void SetValue(object target, object value)
{
try
{
if (_setter == null)
{
_setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(_memberInfo);
}
#if DEBUG
// dynamic method doesn't check whether the type is 'legal' to set
// add this check for unit tests
if (value == null)
{
if (!ReflectionUtils.IsNullable(ReflectionUtils.GetMemberUnderlyingType(_memberInfo)))
{
throw new JsonSerializationException("Incompatible value. Cannot set {0} to null.".FormatWith(CultureInfo.InvariantCulture, _memberInfo));
}
}
else if (!ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsAssignableFrom(value.GetType()))
{
throw new JsonSerializationException("Incompatible value. Cannot set {0} to type {1}.".FormatWith(CultureInfo.InvariantCulture, _memberInfo, value.GetType()));
}
#endif
_setter(target, value);
}
catch (Exception ex)
{
throw new JsonSerializationException("Error setting value to '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex);
}
}
/// <summary>
/// Gets the value.
/// </summary>
/// <param name="target">The target to get the value from.</param>
/// <returns>The value.</returns>
public object GetValue(object target)
{
try
{
if (_getter == null)
{
_getter = DynamicReflectionDelegateFactory.Instance.CreateGet<object>(_memberInfo);
}
return _getter(target);
}
catch (Exception ex)
{
throw new JsonSerializationException("Error getting value from '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex);
}
}
}
}
#endif

View File

@@ -0,0 +1,75 @@
#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;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Provides information surrounding an error.
/// </summary>
public class ErrorContext
{
internal ErrorContext(object originalObject, object member, string path, Exception error)
{
OriginalObject = originalObject;
Member = member;
Error = error;
Path = path;
}
internal bool Traced { get; set; }
/// <summary>
/// Gets the error.
/// </summary>
/// <value>The error.</value>
public Exception Error { get; private set; }
/// <summary>
/// Gets the original object that caused the error.
/// </summary>
/// <value>The original object that caused the error.</value>
public object OriginalObject { get; private set; }
/// <summary>
/// Gets the member that caused the error.
/// </summary>
/// <value>The member that caused the error.</value>
public object Member { get; private set; }
/// <summary>
/// Gets the path of the JSON location where the error occurred.
/// </summary>
/// <value>The path of the JSON location where the error occurred.</value>
public string Path { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ErrorContext"/> is handled.
/// </summary>
/// <value><c>true</c> if handled; otherwise, <c>false</c>.</value>
public bool Handled { get; set; }
}
}

View File

@@ -0,0 +1,58 @@
#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;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Provides data for the Error event.
/// </summary>
public class ErrorEventArgs : EventArgs
{
/// <summary>
/// Gets the current object the error event is being raised against.
/// </summary>
/// <value>The current object the error event is being raised against.</value>
public object CurrentObject { get; private set; }
/// <summary>
/// Gets the error context.
/// </summary>
/// <value>The error context.</value>
public ErrorContext ErrorContext { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="ErrorEventArgs"/> class.
/// </summary>
/// <param name="currentObject">The current object.</param>
/// <param name="errorContext">The error context.</param>
public ErrorEventArgs(object currentObject, ErrorContext errorContext)
{
CurrentObject = currentObject;
ErrorContext = errorContext;
}
}
}

View File

@@ -0,0 +1,120 @@
#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
#if !(NET20 || NET35)
using System;
using System.Collections.Generic;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#endif
using System.Text;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Get and set values for a <see cref="MemberInfo"/> using dynamic methods.
/// </summary>
public class ExpressionValueProvider : IValueProvider
{
private readonly MemberInfo _memberInfo;
private Func<object, object> _getter;
private Action<object, object> _setter;
/// <summary>
/// Initializes a new instance of the <see cref="ExpressionValueProvider"/> class.
/// </summary>
/// <param name="memberInfo">The member info.</param>
public ExpressionValueProvider(MemberInfo memberInfo)
{
ValidationUtils.ArgumentNotNull(memberInfo, nameof(memberInfo));
_memberInfo = memberInfo;
}
/// <summary>
/// Sets the value.
/// </summary>
/// <param name="target">The target to set the value on.</param>
/// <param name="value">The value to set on the target.</param>
public void SetValue(object target, object value)
{
try
{
if (_setter == null)
{
_setter = ExpressionReflectionDelegateFactory.Instance.CreateSet<object>(_memberInfo);
}
#if DEBUG
// dynamic method doesn't check whether the type is 'legal' to set
// add this check for unit tests
if (value == null)
{
if (!ReflectionUtils.IsNullable(ReflectionUtils.GetMemberUnderlyingType(_memberInfo)))
{
throw new JsonSerializationException("Incompatible value. Cannot set {0} to null.".FormatWith(CultureInfo.InvariantCulture, _memberInfo));
}
}
else if (!ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsAssignableFrom(value.GetType()))
{
throw new JsonSerializationException("Incompatible value. Cannot set {0} to type {1}.".FormatWith(CultureInfo.InvariantCulture, _memberInfo, value.GetType()));
}
#endif
_setter(target, value);
}
catch (Exception ex)
{
throw new JsonSerializationException("Error setting value to '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex);
}
}
/// <summary>
/// Gets the value.
/// </summary>
/// <param name="target">The target to get the value from.</param>
/// <returns>The value.</returns>
public object GetValue(object target)
{
try
{
if (_getter == null)
{
_getter = ExpressionReflectionDelegateFactory.Instance.CreateGet<object>(_memberInfo);
}
return _getter(target);
}
catch (Exception ex)
{
throw new JsonSerializationException("Error getting value from '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex);
}
}
}
}
#endif

View File

@@ -0,0 +1,51 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Provides methods to get attributes.
/// </summary>
public interface IAttributeProvider
{
/// <summary>
/// Returns a collection of all of the attributes, or an empty collection if there are no attributes.
/// </summary>
/// <param name="inherit">When true, look up the hierarchy chain for the inherited custom attribute.</param>
/// <returns>A collection of <see cref="Attribute"/>s, or an empty collection.</returns>
IList<Attribute> GetAttributes(bool inherit);
/// <summary>
/// Returns a collection of attributes, identified by type, or an empty collection if there are no attributes.
/// </summary>
/// <param name="attributeType">The type of the attributes.</param>
/// <param name="inherit">When true, look up the hierarchy chain for the inherited custom attribute.</param>
/// <returns>A collection of <see cref="Attribute"/>s, or an empty collection.</returns>
IList<Attribute> GetAttributes(Type attributeType, bool inherit);
}
}

View File

@@ -0,0 +1,46 @@
#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;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Used by <see cref="JsonSerializer"/> to resolves a <see cref="JsonContract"/> for a given <see cref="Type"/>.
/// </summary>
/// <example>
/// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="ReducingSerializedJsonSizeContractResolverObject" title="IContractResolver Class" />
/// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="ReducingSerializedJsonSizeContractResolverExample" title="IContractResolver Example" />
/// </example>
public interface IContractResolver
{
/// <summary>
/// Resolves the contract for a given type.
/// </summary>
/// <param name="type">The type to resolve a contract for.</param>
/// <returns>The contract for a given type.</returns>
JsonContract ResolveContract(Type type);
}
}

View File

@@ -0,0 +1,67 @@
#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
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Used to resolve references when serializing and deserializing JSON by the <see cref="JsonSerializer"/>.
/// </summary>
public interface IReferenceResolver
{
/// <summary>
/// Resolves a reference to its object.
/// </summary>
/// <param name="context">The serialization context.</param>
/// <param name="reference">The reference to resolve.</param>
/// <returns>The object that</returns>
object ResolveReference(object context, string reference);
/// <summary>
/// Gets the reference for the sepecified object.
/// </summary>
/// <param name="context">The serialization context.</param>
/// <param name="value">The object to get a reference for.</param>
/// <returns>The reference to the object.</returns>
string GetReference(object context, object value);
/// <summary>
/// Determines whether the specified object is referenced.
/// </summary>
/// <param name="context">The serialization context.</param>
/// <param name="value">The object to test for a reference.</param>
/// <returns>
/// <c>true</c> if the specified object is referenced; otherwise, <c>false</c>.
/// </returns>
bool IsReferenced(object context, object value);
/// <summary>
/// Adds a reference to the specified object.
/// </summary>
/// <param name="context">The serialization context.</param>
/// <param name="reference">The reference.</param>
/// <param name="value">The object to reference.</param>
void AddReference(object context, string reference, object value);
}
}

View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Represents a trace writer.
/// </summary>
public interface ITraceWriter
{
/// <summary>
/// Gets the <see cref="TraceLevel"/> that will be used to filter the trace messages passed to the writer.
/// For example a filter level of <code>Info</code> will exclude <code>Verbose</code> messages and include <code>Info</code>,
/// <code>Warning</code> and <code>Error</code> messages.
/// </summary>
/// <value>The <see cref="TraceLevel"/> that will be used to filter the trace messages passed to the writer.</value>
TraceLevel LevelFilter { get; }
/// <summary>
/// Writes the specified trace level, message and optional exception.
/// </summary>
/// <param name="level">The <see cref="TraceLevel"/> at which to write this trace.</param>
/// <param name="message">The trace message.</param>
/// <param name="ex">The trace exception. This parameter is optional.</param>
void Trace(TraceLevel level, string message, Exception ex);
}
}

View File

@@ -0,0 +1,47 @@
#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
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Provides methods to get and set values.
/// </summary>
public interface IValueProvider
{
/// <summary>
/// Sets the value.
/// </summary>
/// <param name="target">The target to set the value on.</param>
/// <param name="value">The value to set on the target.</param>
void SetValue(object target, object value);
/// <summary>
/// Gets the value.
/// </summary>
/// <param name="target">The target to get the value from.</param>
/// <returns>The value.</returns>
object GetValue(object target);
}
}

View File

@@ -0,0 +1,310 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Collections;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonArrayContract : JsonContainerContract
{
/// <summary>
/// Gets the <see cref="System.Type"/> of the collection items.
/// </summary>
/// <value>The <see cref="System.Type"/> of the collection items.</value>
public Type CollectionItemType { get; private set; }
/// <summary>
/// Gets a value indicating whether the collection type is a multidimensional array.
/// </summary>
/// <value><c>true</c> if the collection type is a multidimensional array; otherwise, <c>false</c>.</value>
public bool IsMultidimensionalArray { get; private set; }
private readonly Type _genericCollectionDefinitionType;
private Type _genericWrapperType;
private ObjectConstructor<object> _genericWrapperCreator;
private Func<object> _genericTemporaryCollectionCreator;
internal bool IsArray { get; private set; }
internal bool ShouldCreateWrapper { get; private set; }
internal bool CanDeserialize { get; private set; }
private readonly ConstructorInfo _parameterizedConstructor;
private ObjectConstructor<object> _parameterizedCreator;
private ObjectConstructor<object> _overrideCreator;
internal ObjectConstructor<object> ParameterizedCreator
{
get
{
if (_parameterizedCreator == null)
{
_parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor);
}
return _parameterizedCreator;
}
}
/// <summary>
/// Gets or sets the function used to create the object. When set this function will override <see cref="JsonContract.DefaultCreator"/>.
/// </summary>
/// <value>The function used to create the object.</value>
public ObjectConstructor<object> OverrideCreator
{
get { return _overrideCreator; }
set
{
_overrideCreator = value;
// hacky
CanDeserialize = true;
}
}
/// <summary>
/// Gets a value indicating whether the creator has a parameter with the collection values.
/// </summary>
/// <value><c>true</c> if the creator has a parameter with the collection values; otherwise, <c>false</c>.</value>
public bool HasParameterizedCreator { get; set; }
internal bool HasParameterizedCreatorInternal
{
get { return (HasParameterizedCreator || _parameterizedCreator != null || _parameterizedConstructor != null); }
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonArrayContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonArrayContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Array;
IsArray = CreatedType.IsArray;
bool canDeserialize;
Type tempCollectionType;
if (IsArray)
{
CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType);
IsReadOnlyOrFixedSize = true;
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
canDeserialize = true;
IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1);
}
else if (typeof(IList).IsAssignableFrom(underlyingType))
{
if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
{
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
}
else
{
CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType);
}
if (underlyingType == typeof(IList))
{
CreatedType = typeof(List<object>);
}
if (CollectionItemType != null)
{
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
}
IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>));
canDeserialize = true;
}
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType))
{
CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>)))
{
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
}
#if !(NET20 || NET35)
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>)))
{
CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType);
}
#endif
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
canDeserialize = true;
ShouldCreateWrapper = true;
}
#if !(NET40 || NET35 || NET20 || PORTABLE40)
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>), out tempCollectionType))
{
CollectionItemType = tempCollectionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>))
|| ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList<>)))
{
CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType);
}
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, CollectionItemType);
IsReadOnlyOrFixedSize = true;
canDeserialize = HasParameterizedCreatorInternal;
}
#endif
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType))
{
CollectionItemType = tempCollectionType.GetGenericArguments()[0];
if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>)))
{
CreatedType = typeof(List<>).MakeGenericType(CollectionItemType);
}
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
#if !(NET35 || NET20)
if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpListTypeName)
{
FSharpUtils.EnsureInitialized(underlyingType.Assembly());
_parameterizedCreator = FSharpUtils.CreateSeq(CollectionItemType);
}
#endif
if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
_genericCollectionDefinitionType = tempCollectionType;
IsReadOnlyOrFixedSize = false;
ShouldCreateWrapper = false;
canDeserialize = true;
}
else
{
_genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType);
IsReadOnlyOrFixedSize = true;
ShouldCreateWrapper = true;
canDeserialize = HasParameterizedCreatorInternal;
}
}
else
{
// types that implement IEnumerable and nothing else
canDeserialize = false;
ShouldCreateWrapper = true;
}
CanDeserialize = canDeserialize;
#if (NET20 || NET35)
if (CollectionItemType != null && ReflectionUtils.IsNullableType(CollectionItemType))
{
// bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object)
// wrapper will handle calling Add(T) instead
if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType)
|| (IsArray && !IsMultidimensionalArray))
{
ShouldCreateWrapper = true;
}
}
#endif
#if !(NET20 || NET35 || NET40)
Type immutableCreatedType;
ObjectConstructor<object> immutableParameterizedCreator;
if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator))
{
CreatedType = immutableCreatedType;
_parameterizedCreator = immutableParameterizedCreator;
IsReadOnlyOrFixedSize = true;
CanDeserialize = true;
}
#endif
}
internal IWrappedCollection CreateWrapper(object list)
{
if (_genericWrapperCreator == null)
{
_genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType);
Type constructorArgument;
if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>))
|| _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType);
}
else
{
constructorArgument = _genericCollectionDefinitionType;
}
ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument });
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor);
}
return (IWrappedCollection)_genericWrapperCreator(list);
}
internal IList CreateTemporaryCollection()
{
if (_genericTemporaryCollectionCreator == null)
{
// multidimensional array will also have array instances in it
Type collectionItemType = (IsMultidimensionalArray || CollectionItemType == null)
? typeof(object)
: CollectionItemType;
Type temporaryListType = typeof(List<>).MakeGenericType(collectionItemType);
_genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryListType);
}
return (IList)_genericTemporaryCollectionCreator();
}
}
}

View File

@@ -0,0 +1,120 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Collections;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonContainerContract : JsonContract
{
private JsonContract _itemContract;
private JsonContract _finalItemContract;
// will be null for containers that don't have an item type (e.g. IList) or for complex objects
internal JsonContract ItemContract
{
get { return _itemContract; }
set
{
_itemContract = value;
if (_itemContract != null)
{
_finalItemContract = (_itemContract.UnderlyingType.IsSealed()) ? _itemContract : null;
}
else
{
_finalItemContract = null;
}
}
}
// the final (i.e. can't be inherited from like a sealed class or valuetype) item contract
internal JsonContract FinalItemContract
{
get { return _finalItemContract; }
}
/// <summary>
/// Gets or sets the default collection items <see cref="JsonConverter" />.
/// </summary>
/// <value>The converter.</value>
public JsonConverter ItemConverter { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the collection items preserve object references.
/// </summary>
/// <value><c>true</c> if collection items preserve object references; otherwise, <c>false</c>.</value>
public bool? ItemIsReference { get; set; }
/// <summary>
/// Gets or sets the collection item reference loop handling.
/// </summary>
/// <value>The reference loop handling.</value>
public ReferenceLoopHandling? ItemReferenceLoopHandling { get; set; }
/// <summary>
/// Gets or sets the collection item type name handling.
/// </summary>
/// <value>The type name handling.</value>
public TypeNameHandling? ItemTypeNameHandling { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonContainerContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
internal JsonContainerContract(Type underlyingType)
: base(underlyingType)
{
JsonContainerAttribute jsonContainerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(underlyingType);
if (jsonContainerAttribute != null)
{
if (jsonContainerAttribute.ItemConverterType != null)
{
ItemConverter = JsonTypeReflector.CreateJsonConverterInstance(
jsonContainerAttribute.ItemConverterType,
jsonContainerAttribute.ItemConverterParameters);
}
ItemIsReference = jsonContainerAttribute._itemIsReference;
ItemReferenceLoopHandling = jsonContainerAttribute._itemReferenceLoopHandling;
ItemTypeNameHandling = jsonContainerAttribute._itemTypeNameHandling;
}
}
}
}

View File

@@ -0,0 +1,392 @@
#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.Reflection;
using System.Runtime.Serialization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization
{
internal enum JsonContractType
{
None = 0,
Object = 1,
Array = 2,
Primitive = 3,
String = 4,
Dictionary = 5,
Dynamic = 6,
Serializable = 7,
Linq = 8
}
/// <summary>
/// Handles <see cref="JsonSerializer"/> serialization callback events.
/// </summary>
/// <param name="o">The object that raised the callback event.</param>
/// <param name="context">The streaming context.</param>
public delegate void SerializationCallback(object o, StreamingContext context);
/// <summary>
/// Handles <see cref="JsonSerializer"/> serialization error callback events.
/// </summary>
/// <param name="o">The object that raised the callback event.</param>
/// <param name="context">The streaming context.</param>
/// <param name="errorContext">The error context.</param>
public delegate void SerializationErrorCallback(object o, StreamingContext context, ErrorContext errorContext);
/// <summary>
/// Sets extension data for an object during deserialization.
/// </summary>
/// <param name="o">The object to set extension data on.</param>
/// <param name="key">The extension data key.</param>
/// <param name="value">The extension data value.</param>
public delegate void ExtensionDataSetter(object o, string key, object value);
/// <summary>
/// Gets extension data for an object during serialization.
/// </summary>
/// <param name="o">The object to set extension data on.</param>
public delegate IEnumerable<KeyValuePair<object, object>> ExtensionDataGetter(object o);
/// <summary>
/// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public abstract class JsonContract
{
internal bool IsNullable;
internal bool IsConvertable;
internal bool IsEnum;
internal Type NonNullableUnderlyingType;
internal ReadType InternalReadType;
internal JsonContractType ContractType;
internal bool IsReadOnlyOrFixedSize;
internal bool IsSealed;
internal bool IsInstantiable;
private List<SerializationCallback> _onDeserializedCallbacks;
private IList<SerializationCallback> _onDeserializingCallbacks;
private IList<SerializationCallback> _onSerializedCallbacks;
private IList<SerializationCallback> _onSerializingCallbacks;
private IList<SerializationErrorCallback> _onErrorCallbacks;
private Type _createdType;
/// <summary>
/// Gets the underlying type for the contract.
/// </summary>
/// <value>The underlying type for the contract.</value>
public Type UnderlyingType { get; private set; }
/// <summary>
/// Gets or sets the type created during deserialization.
/// </summary>
/// <value>The type created during deserialization.</value>
public Type CreatedType
{
get { return _createdType; }
set
{
_createdType = value;
IsSealed = _createdType.IsSealed();
IsInstantiable = !(_createdType.IsInterface() || _createdType.IsAbstract());
}
}
/// <summary>
/// Gets or sets whether this type contract is serialized as a reference.
/// </summary>
/// <value>Whether this type contract is serialized as a reference.</value>
public bool? IsReference { get; set; }
/// <summary>
/// Gets or sets the default <see cref="JsonConverter" /> for this contract.
/// </summary>
/// <value>The converter.</value>
public JsonConverter Converter { get; set; }
// internally specified JsonConverter's to override default behavour
// checked for after passed in converters and attribute specified converters
internal JsonConverter InternalConverter { get; set; }
/// <summary>
/// Gets or sets all methods called immediately after deserialization of the object.
/// </summary>
/// <value>The methods called immediately after deserialization of the object.</value>
public IList<SerializationCallback> OnDeserializedCallbacks
{
get
{
if (_onDeserializedCallbacks == null)
{
_onDeserializedCallbacks = new List<SerializationCallback>();
}
return _onDeserializedCallbacks;
}
}
/// <summary>
/// Gets or sets all methods called during deserialization of the object.
/// </summary>
/// <value>The methods called during deserialization of the object.</value>
public IList<SerializationCallback> OnDeserializingCallbacks
{
get
{
if (_onDeserializingCallbacks == null)
{
_onDeserializingCallbacks = new List<SerializationCallback>();
}
return _onDeserializingCallbacks;
}
}
/// <summary>
/// Gets or sets all methods called after serialization of the object graph.
/// </summary>
/// <value>The methods called after serialization of the object graph.</value>
public IList<SerializationCallback> OnSerializedCallbacks
{
get
{
if (_onSerializedCallbacks == null)
{
_onSerializedCallbacks = new List<SerializationCallback>();
}
return _onSerializedCallbacks;
}
}
/// <summary>
/// Gets or sets all methods called before serialization of the object.
/// </summary>
/// <value>The methods called before serialization of the object.</value>
public IList<SerializationCallback> OnSerializingCallbacks
{
get
{
if (_onSerializingCallbacks == null)
{
_onSerializingCallbacks = new List<SerializationCallback>();
}
return _onSerializingCallbacks;
}
}
/// <summary>
/// Gets or sets all method called when an error is thrown during the serialization of the object.
/// </summary>
/// <value>The methods called when an error is thrown during the serialization of the object.</value>
public IList<SerializationErrorCallback> OnErrorCallbacks
{
get
{
if (_onErrorCallbacks == null)
{
_onErrorCallbacks = new List<SerializationErrorCallback>();
}
return _onErrorCallbacks;
}
}
/// <summary>
/// Gets or sets the method called immediately after deserialization of the object.
/// </summary>
/// <value>The method called immediately after deserialization of the object.</value>
[Obsolete("This property is obsolete and has been replaced by the OnDeserializedCallbacks collection.")]
public MethodInfo OnDeserialized
{
get { return (OnDeserializedCallbacks.Count > 0) ? OnDeserializedCallbacks[0].Method() : null; }
set
{
OnDeserializedCallbacks.Clear();
OnDeserializedCallbacks.Add(CreateSerializationCallback(value));
}
}
/// <summary>
/// Gets or sets the method called during deserialization of the object.
/// </summary>
/// <value>The method called during deserialization of the object.</value>
[Obsolete("This property is obsolete and has been replaced by the OnDeserializingCallbacks collection.")]
public MethodInfo OnDeserializing
{
get { return (OnDeserializingCallbacks.Count > 0) ? OnDeserializingCallbacks[0].Method() : null; }
set
{
OnDeserializingCallbacks.Clear();
OnDeserializingCallbacks.Add(CreateSerializationCallback(value));
}
}
/// <summary>
/// Gets or sets the method called after serialization of the object graph.
/// </summary>
/// <value>The method called after serialization of the object graph.</value>
[Obsolete("This property is obsolete and has been replaced by the OnSerializedCallbacks collection.")]
public MethodInfo OnSerialized
{
get { return (OnSerializedCallbacks.Count > 0) ? OnSerializedCallbacks[0].Method() : null; }
set
{
OnSerializedCallbacks.Clear();
OnSerializedCallbacks.Add(CreateSerializationCallback(value));
}
}
/// <summary>
/// Gets or sets the method called before serialization of the object.
/// </summary>
/// <value>The method called before serialization of the object.</value>
[Obsolete("This property is obsolete and has been replaced by the OnSerializingCallbacks collection.")]
public MethodInfo OnSerializing
{
get { return (OnSerializingCallbacks.Count > 0) ? OnSerializingCallbacks[0].Method() : null; }
set
{
OnSerializingCallbacks.Clear();
OnSerializingCallbacks.Add(CreateSerializationCallback(value));
}
}
/// <summary>
/// Gets or sets the method called when an error is thrown during the serialization of the object.
/// </summary>
/// <value>The method called when an error is thrown during the serialization of the object.</value>
[Obsolete("This property is obsolete and has been replaced by the OnErrorCallbacks collection.")]
public MethodInfo OnError
{
get { return (OnErrorCallbacks.Count > 0) ? OnErrorCallbacks[0].Method() : null; }
set
{
OnErrorCallbacks.Clear();
OnErrorCallbacks.Add(CreateSerializationErrorCallback(value));
}
}
/// <summary>
/// Gets or sets the default creator method used to create the object.
/// </summary>
/// <value>The default creator method used to create the object.</value>
public Func<object> DefaultCreator { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the default creator is non public.
/// </summary>
/// <value><c>true</c> if the default object creator is non-public; otherwise, <c>false</c>.</value>
public bool DefaultCreatorNonPublic { get; set; }
internal JsonContract(Type underlyingType)
{
ValidationUtils.ArgumentNotNull(underlyingType, nameof(underlyingType));
UnderlyingType = underlyingType;
IsNullable = ReflectionUtils.IsNullable(underlyingType);
NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType;
CreatedType = NonNullableUnderlyingType;
IsConvertable = ConvertUtils.IsConvertible(NonNullableUnderlyingType);
IsEnum = NonNullableUnderlyingType.IsEnum();
InternalReadType = ReadType.Read;
}
internal void InvokeOnSerializing(object o, StreamingContext context)
{
if (_onSerializingCallbacks != null)
{
foreach (SerializationCallback callback in _onSerializingCallbacks)
{
callback(o, context);
}
}
}
internal void InvokeOnSerialized(object o, StreamingContext context)
{
if (_onSerializedCallbacks != null)
{
foreach (SerializationCallback callback in _onSerializedCallbacks)
{
callback(o, context);
}
}
}
internal void InvokeOnDeserializing(object o, StreamingContext context)
{
if (_onDeserializingCallbacks != null)
{
foreach (SerializationCallback callback in _onDeserializingCallbacks)
{
callback(o, context);
}
}
}
internal void InvokeOnDeserialized(object o, StreamingContext context)
{
if (_onDeserializedCallbacks != null)
{
foreach (SerializationCallback callback in _onDeserializedCallbacks)
{
callback(o, context);
}
}
}
internal void InvokeOnError(object o, StreamingContext context, ErrorContext errorContext)
{
if (_onErrorCallbacks != null)
{
foreach (SerializationErrorCallback callback in _onErrorCallbacks)
{
callback(o, context, errorContext);
}
}
}
internal static SerializationCallback CreateSerializationCallback(MethodInfo callbackMethodInfo)
{
return (o, context) => callbackMethodInfo.Invoke(o, new object[] { context });
}
internal static SerializationErrorCallback CreateSerializationErrorCallback(MethodInfo callbackMethodInfo)
{
return (o, context, econtext) => callbackMethodInfo.Invoke(o, new object[] { context, econtext });
}
}
}

View File

@@ -0,0 +1,242 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Collections;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#endif
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonDictionaryContract : JsonContainerContract
{
/// <summary>
/// Gets or sets the property name resolver.
/// </summary>
/// <value>The property name resolver.</value>
[Obsolete("PropertyNameResolver is obsolete. Use DictionaryKeyResolver instead.")]
public Func<string, string> PropertyNameResolver
{
get { return DictionaryKeyResolver; }
set { DictionaryKeyResolver = value; }
}
/// <summary>
/// Gets or sets the dictionary key resolver.
/// </summary>
/// <value>The dictionary key resolver.</value>
public Func<string, string> DictionaryKeyResolver { get; set; }
/// <summary>
/// Gets the <see cref="System.Type"/> of the dictionary keys.
/// </summary>
/// <value>The <see cref="System.Type"/> of the dictionary keys.</value>
public Type DictionaryKeyType { get; private set; }
/// <summary>
/// Gets the <see cref="System.Type"/> of the dictionary values.
/// </summary>
/// <value>The <see cref="System.Type"/> of the dictionary values.</value>
public Type DictionaryValueType { get; private set; }
internal JsonContract KeyContract { get; set; }
private readonly Type _genericCollectionDefinitionType;
private Type _genericWrapperType;
private ObjectConstructor<object> _genericWrapperCreator;
private Func<object> _genericTemporaryDictionaryCreator;
internal bool ShouldCreateWrapper { get; private set; }
private readonly ConstructorInfo _parameterizedConstructor;
private ObjectConstructor<object> _overrideCreator;
private ObjectConstructor<object> _parameterizedCreator;
internal ObjectConstructor<object> ParameterizedCreator
{
get
{
if (_parameterizedCreator == null)
{
_parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor);
}
return _parameterizedCreator;
}
}
/// <summary>
/// Gets or sets the function used to create the object. When set this function will override <see cref="JsonContract.DefaultCreator"/>.
/// </summary>
/// <value>The function used to create the object.</value>
public ObjectConstructor<object> OverrideCreator
{
get { return _overrideCreator; }
set { _overrideCreator = value; }
}
/// <summary>
/// Gets a value indicating whether the creator has a parameter with the dictionary values.
/// </summary>
/// <value><c>true</c> if the creator has a parameter with the dictionary values; otherwise, <c>false</c>.</value>
public bool HasParameterizedCreator { get; set; }
internal bool HasParameterizedCreatorInternal
{
get { return (HasParameterizedCreator || _parameterizedCreator != null || _parameterizedConstructor != null); }
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonDictionaryContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonDictionaryContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Dictionary;
Type keyType;
Type valueType;
if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IDictionary<,>), out _genericCollectionDefinitionType))
{
keyType = _genericCollectionDefinitionType.GetGenericArguments()[0];
valueType = _genericCollectionDefinitionType.GetGenericArguments()[1];
if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary<,>)))
{
CreatedType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
}
#if !(NET40 || NET35 || NET20 || PORTABLE40)
IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyDictionary<,>));
#endif
}
#if !(NET40 || NET35 || NET20 || PORTABLE40)
else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyDictionary<,>), out _genericCollectionDefinitionType))
{
keyType = _genericCollectionDefinitionType.GetGenericArguments()[0];
valueType = _genericCollectionDefinitionType.GetGenericArguments()[1];
if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IReadOnlyDictionary<,>)))
{
CreatedType = typeof(ReadOnlyDictionary<,>).MakeGenericType(keyType, valueType);
}
IsReadOnlyOrFixedSize = true;
}
#endif
else
{
ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType);
if (UnderlyingType == typeof(IDictionary))
{
CreatedType = typeof(Dictionary<object, object>);
}
}
if (keyType != null && valueType != null)
{
_parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType));
#if !(NET35 || NET20)
if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpMapTypeName)
{
FSharpUtils.EnsureInitialized(underlyingType.Assembly());
_parameterizedCreator = FSharpUtils.CreateMap(keyType, valueType);
}
#endif
}
ShouldCreateWrapper = !typeof(IDictionary).IsAssignableFrom(CreatedType);
DictionaryKeyType = keyType;
DictionaryValueType = valueType;
#if (NET20 || NET35)
if (DictionaryValueType != null && ReflectionUtils.IsNullableType(DictionaryValueType))
{
Type tempDictioanryType;
// bug in .NET 2.0 & 3.5 that Dictionary<TKey, Nullable<TValue>> throws an error when adding null via IDictionary[key] = object
// wrapper will handle calling Add(T) instead
if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out tempDictioanryType))
{
ShouldCreateWrapper = true;
}
}
#endif
#if !(NET20 || NET35 || NET40)
Type immutableCreatedType;
ObjectConstructor<object> immutableParameterizedCreator;
if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract(underlyingType, DictionaryKeyType, DictionaryValueType, out immutableCreatedType, out immutableParameterizedCreator))
{
CreatedType = immutableCreatedType;
_parameterizedCreator = immutableParameterizedCreator;
IsReadOnlyOrFixedSize = true;
}
#endif
}
internal IWrappedDictionary CreateWrapper(object dictionary)
{
if (_genericWrapperCreator == null)
{
_genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType);
ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType });
_genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor);
}
return (IWrappedDictionary)_genericWrapperCreator(dictionary);
}
internal IDictionary CreateTemporaryDictionary()
{
if (_genericTemporaryDictionaryCreator == null)
{
Type temporaryDictionaryType = typeof(Dictionary<,>).MakeGenericType(DictionaryKeyType ?? typeof(object), DictionaryValueType ?? typeof(object));
_genericTemporaryDictionaryCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryDictionaryType);
}
return (IDictionary)_genericTemporaryDictionaryCreator();
}
}
}

View File

@@ -0,0 +1,119 @@
#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
#if !(NET35 || NET20 || PORTABLE40)
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection;
using System.Runtime.CompilerServices;
using Newtonsoft.Json.Utilities;
using System.Collections;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonDynamicContract : JsonContainerContract
{
/// <summary>
/// Gets the object's properties.
/// </summary>
/// <value>The object's properties.</value>
public JsonPropertyCollection Properties { get; private set; }
/// <summary>
/// Gets or sets the property name resolver.
/// </summary>
/// <value>The property name resolver.</value>
public Func<string, string> PropertyNameResolver { get; set; }
private readonly ThreadSafeStore<string, CallSite<Func<CallSite, object, object>>> _callSiteGetters =
new ThreadSafeStore<string, CallSite<Func<CallSite, object, object>>>(CreateCallSiteGetter);
private readonly ThreadSafeStore<string, CallSite<Func<CallSite, object, object, object>>> _callSiteSetters =
new ThreadSafeStore<string, CallSite<Func<CallSite, object, object, object>>>(CreateCallSiteSetter);
private static CallSite<Func<CallSite, object, object>> CreateCallSiteGetter(string name)
{
GetMemberBinder getMemberBinder = (GetMemberBinder)DynamicUtils.BinderWrapper.GetMember(name, typeof(DynamicUtils));
return CallSite<Func<CallSite, object, object>>.Create(new NoThrowGetBinderMember(getMemberBinder));
}
private static CallSite<Func<CallSite, object, object, object>> CreateCallSiteSetter(string name)
{
SetMemberBinder binder = (SetMemberBinder)DynamicUtils.BinderWrapper.SetMember(name, typeof(DynamicUtils));
return CallSite<Func<CallSite, object, object, object>>.Create(new NoThrowSetBinderMember(binder));
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonDynamicContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonDynamicContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Dynamic;
Properties = new JsonPropertyCollection(UnderlyingType);
}
internal bool TryGetMember(IDynamicMetaObjectProvider dynamicProvider, string name, out object value)
{
ValidationUtils.ArgumentNotNull(dynamicProvider, nameof(dynamicProvider));
CallSite<Func<CallSite, object, object>> callSite = _callSiteGetters.Get(name);
object result = callSite.Target(callSite, dynamicProvider);
if (!ReferenceEquals(result, NoThrowExpressionVisitor.ErrorResult))
{
value = result;
return true;
}
else
{
value = null;
return false;
}
}
internal bool TrySetMember(IDynamicMetaObjectProvider dynamicProvider, string name, object value)
{
ValidationUtils.ArgumentNotNull(dynamicProvider, nameof(dynamicProvider));
CallSite<Func<CallSite, object, object, object>> callSite = _callSiteSetters.Get(name);
object result = callSite.Target(callSite, dynamicProvider, value);
return !ReferenceEquals(result, NoThrowExpressionVisitor.ErrorResult);
}
}
}
#endif

View File

@@ -0,0 +1,161 @@
#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
#if !(DOTNET || PORTABLE40 || PORTABLE)
using System;
using System.Globalization;
using System.Runtime.Serialization;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Serialization
{
internal class JsonFormatterConverter : IFormatterConverter
{
private readonly JsonSerializerInternalReader _reader;
private readonly JsonISerializableContract _contract;
private readonly JsonProperty _member;
public JsonFormatterConverter(JsonSerializerInternalReader reader, JsonISerializableContract contract, JsonProperty member)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
ValidationUtils.ArgumentNotNull(contract, nameof(contract));
_reader = reader;
_contract = contract;
_member = member;
}
private T GetTokenValue<T>(object value)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
JValue v = (JValue)value;
return (T)System.Convert.ChangeType(v.Value, typeof(T), CultureInfo.InvariantCulture);
}
public object Convert(object value, Type type)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
JToken token = value as JToken;
if (token == null)
{
throw new ArgumentException("Value is not a JToken.", nameof(value));
}
return _reader.CreateISerializableItem(token, type, _contract, _member);
}
public object Convert(object value, TypeCode typeCode)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
if (value is JValue)
{
value = ((JValue)value).Value;
}
return System.Convert.ChangeType(value, typeCode, CultureInfo.InvariantCulture);
}
public bool ToBoolean(object value)
{
return GetTokenValue<bool>(value);
}
public byte ToByte(object value)
{
return GetTokenValue<byte>(value);
}
public char ToChar(object value)
{
return GetTokenValue<char>(value);
}
public DateTime ToDateTime(object value)
{
return GetTokenValue<DateTime>(value);
}
public decimal ToDecimal(object value)
{
return GetTokenValue<decimal>(value);
}
public double ToDouble(object value)
{
return GetTokenValue<double>(value);
}
public short ToInt16(object value)
{
return GetTokenValue<short>(value);
}
public int ToInt32(object value)
{
return GetTokenValue<int>(value);
}
public long ToInt64(object value)
{
return GetTokenValue<long>(value);
}
public sbyte ToSByte(object value)
{
return GetTokenValue<sbyte>(value);
}
public float ToSingle(object value)
{
return GetTokenValue<float>(value);
}
public string ToString(object value)
{
return GetTokenValue<string>(value);
}
public ushort ToUInt16(object value)
{
return GetTokenValue<ushort>(value);
}
public uint ToUInt32(object value)
{
return GetTokenValue<uint>(value);
}
public ulong ToUInt64(object value)
{
return GetTokenValue<ulong>(value);
}
}
}
#endif

View File

@@ -0,0 +1,55 @@
#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
#if !(DOTNET || PORTABLE || PORTABLE40)
using System;
using System.Runtime.Serialization;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonISerializableContract : JsonContainerContract
{
/// <summary>
/// Gets or sets the ISerializable object constructor.
/// </summary>
/// <value>The ISerializable object constructor.</value>
public ObjectConstructor<object> ISerializableCreator { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonISerializableContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonISerializableContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Serializable;
}
}
}
#endif

View File

@@ -0,0 +1,45 @@
#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;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonLinqContract : JsonContract
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonLinqContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonLinqContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Linq;
}
}
}

View File

@@ -0,0 +1,227 @@
#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.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonObjectContract : JsonContainerContract
{
/// <summary>
/// Gets or sets the object member serialization.
/// </summary>
/// <value>The member object serialization.</value>
public MemberSerialization MemberSerialization { get; set; }
/// <summary>
/// Gets or sets a value that indicates whether the object's properties are required.
/// </summary>
/// <value>
/// A value indicating whether the object's properties are required.
/// </value>
public Required? ItemRequired { get; set; }
/// <summary>
/// Gets the object's properties.
/// </summary>
/// <value>The object's properties.</value>
public JsonPropertyCollection Properties { get; private set; }
/// <summary>
/// Gets the constructor parameters required for any non-default constructor
/// </summary>
[Obsolete("ConstructorParameters is obsolete. Use CreatorParameters instead.")]
public JsonPropertyCollection ConstructorParameters
{
get { return CreatorParameters; }
}
/// <summary>
/// Gets a collection of <see cref="JsonProperty"/> instances that define the parameters used with <see cref="OverrideCreator"/>.
/// </summary>
public JsonPropertyCollection CreatorParameters
{
get
{
if (_creatorParameters == null)
{
_creatorParameters = new JsonPropertyCollection(UnderlyingType);
}
return _creatorParameters;
}
}
/// <summary>
/// Gets or sets the override constructor used to create the object.
/// This is set when a constructor is marked up using the
/// JsonConstructor attribute.
/// </summary>
/// <value>The override constructor.</value>
[Obsolete("OverrideConstructor is obsolete. Use OverrideCreator instead.")]
public ConstructorInfo OverrideConstructor
{
get { return _overrideConstructor; }
set
{
_overrideConstructor = value;
_overrideCreator = (value != null) ? JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(value) : null;
}
}
/// <summary>
/// Gets or sets the parametrized constructor used to create the object.
/// </summary>
/// <value>The parametrized constructor.</value>
[Obsolete("ParametrizedConstructor is obsolete. Use OverrideCreator instead.")]
public ConstructorInfo ParametrizedConstructor
{
get { return _parametrizedConstructor; }
set
{
_parametrizedConstructor = value;
_parameterizedCreator = (value != null) ? JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(value) : null;
}
}
/// <summary>
/// Gets or sets the function used to create the object. When set this function will override <see cref="JsonContract.DefaultCreator"/>.
/// This function is called with a collection of arguments which are defined by the <see cref="CreatorParameters"/> collection.
/// </summary>
/// <value>The function used to create the object.</value>
public ObjectConstructor<object> OverrideCreator
{
get { return _overrideCreator; }
set
{
_overrideCreator = value;
_overrideConstructor = null;
}
}
internal ObjectConstructor<object> ParameterizedCreator
{
get { return _parameterizedCreator; }
}
/// <summary>
/// Gets or sets the extension data setter.
/// </summary>
public ExtensionDataSetter ExtensionDataSetter { get; set; }
/// <summary>
/// Gets or sets the extension data getter.
/// </summary>
public ExtensionDataGetter ExtensionDataGetter { get; set; }
/// <summary>
/// Gets or sets the extension data value type.
/// </summary>
public Type ExtensionDataValueType
{
get { return _extensionDataValueType; }
set
{
_extensionDataValueType = value;
ExtensionDataIsJToken = (value != null && typeof(JToken).IsAssignableFrom(value));
}
}
internal bool ExtensionDataIsJToken;
private bool? _hasRequiredOrDefaultValueProperties;
private ConstructorInfo _parametrizedConstructor;
private ConstructorInfo _overrideConstructor;
private ObjectConstructor<object> _overrideCreator;
private ObjectConstructor<object> _parameterizedCreator;
private JsonPropertyCollection _creatorParameters;
private Type _extensionDataValueType;
internal bool HasRequiredOrDefaultValueProperties
{
get
{
if (_hasRequiredOrDefaultValueProperties == null)
{
_hasRequiredOrDefaultValueProperties = false;
if (ItemRequired.GetValueOrDefault(Required.Default) != Required.Default)
{
_hasRequiredOrDefaultValueProperties = true;
}
else
{
foreach (JsonProperty property in Properties)
{
if (property.Required != Required.Default || (property.DefaultValueHandling & DefaultValueHandling.Populate) == DefaultValueHandling.Populate)
{
_hasRequiredOrDefaultValueProperties = true;
break;
}
}
}
}
return _hasRequiredOrDefaultValueProperties.GetValueOrDefault();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonObjectContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonObjectContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Object;
Properties = new JsonPropertyCollection(UnderlyingType);
}
#if !(DOTNET || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35)
[SecuritySafeCritical]
#endif
internal object GetUninitializedObject()
{
// we should never get here if the environment is not fully trusted, check just in case
if (!JsonTypeReflector.FullyTrusted)
{
throw new JsonException("Insufficient permissions. Creating an uninitialized '{0}' type requires full trust.".FormatWith(CultureInfo.InvariantCulture, NonNullableUnderlyingType));
}
return FormatterServices.GetUninitializedObject(NonNullableUnderlyingType);
}
#endif
}
}

View File

@@ -0,0 +1,75 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonPrimitiveContract : JsonContract
{
internal PrimitiveTypeCode TypeCode { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonPrimitiveContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonPrimitiveContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.Primitive;
TypeCode = ConvertUtils.GetTypeCode(underlyingType);
IsReadOnlyOrFixedSize = true;
ReadType readType;
if (ReadTypeMap.TryGetValue(NonNullableUnderlyingType, out readType))
{
InternalReadType = readType;
}
}
private static readonly Dictionary<Type, ReadType> ReadTypeMap = new Dictionary<Type, ReadType>
{
[typeof(byte[])] = ReadType.ReadAsBytes,
[typeof(byte)] = ReadType.ReadAsInt32,
[typeof(short)] = ReadType.ReadAsInt32,
[typeof(int)] = ReadType.ReadAsInt32,
[typeof(decimal)] = ReadType.ReadAsDecimal,
[typeof(bool)] = ReadType.ReadAsBoolean,
[typeof(string)] = ReadType.ReadAsString,
[typeof(DateTime)] = ReadType.ReadAsDateTime,
#if !NET20
[typeof(DateTimeOffset)] = ReadType.ReadAsDateTimeOffset,
#endif
[typeof(float)] = ReadType.ReadAsDouble,
[typeof(double)] = ReadType.ReadAsDouble
};
}
}

View File

@@ -0,0 +1,308 @@
#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.Reflection;
using Newtonsoft.Json.Utilities;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#endif
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Maps a JSON property to a .NET member or constructor parameter.
/// </summary>
public class JsonProperty
{
internal Required? _required;
internal bool _hasExplicitDefaultValue;
private object _defaultValue;
private bool _hasGeneratedDefaultValue;
private string _propertyName;
internal bool _skipPropertyNameEscape;
private Type _propertyType;
// use to cache contract during deserialization
internal JsonContract PropertyContract { get; set; }
/// <summary>
/// Gets or sets the name of the property.
/// </summary>
/// <value>The name of the property.</value>
public string PropertyName
{
get { return _propertyName; }
set
{
_propertyName = value;
_skipPropertyNameEscape = !JavaScriptUtils.ShouldEscapeJavaScriptString(_propertyName, JavaScriptUtils.HtmlCharEscapeFlags);
}
}
/// <summary>
/// Gets or sets the type that declared this property.
/// </summary>
/// <value>The type that declared this property.</value>
public Type DeclaringType { get; set; }
/// <summary>
/// Gets or sets the order of serialization of a member.
/// </summary>
/// <value>The numeric order of serialization.</value>
public int? Order { get; set; }
/// <summary>
/// Gets or sets the name of the underlying member or parameter.
/// </summary>
/// <value>The name of the underlying member or parameter.</value>
public string UnderlyingName { get; set; }
/// <summary>
/// Gets the <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.
/// </summary>
/// <value>The <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.</value>
public IValueProvider ValueProvider { get; set; }
/// <summary>
/// Gets or sets the <see cref="IAttributeProvider"/> for this property.
/// </summary>
/// <value>The <see cref="IAttributeProvider"/> for this property.</value>
public IAttributeProvider AttributeProvider { get; set; }
/// <summary>
/// Gets or sets the type of the property.
/// </summary>
/// <value>The type of the property.</value>
public Type PropertyType
{
get { return _propertyType; }
set
{
if (_propertyType != value)
{
_propertyType = value;
_hasGeneratedDefaultValue = false;
}
}
}
/// <summary>
/// Gets or sets the <see cref="JsonConverter" /> for the property.
/// If set this converter takes presidence over the contract converter for the property type.
/// </summary>
/// <value>The converter.</value>
public JsonConverter Converter { get; set; }
/// <summary>
/// Gets or sets the member converter.
/// </summary>
/// <value>The member converter.</value>
public JsonConverter MemberConverter { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is ignored.
/// </summary>
/// <value><c>true</c> if ignored; otherwise, <c>false</c>.</value>
public bool Ignored { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is readable.
/// </summary>
/// <value><c>true</c> if readable; otherwise, <c>false</c>.</value>
public bool Readable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is writable.
/// </summary>
/// <value><c>true</c> if writable; otherwise, <c>false</c>.</value>
public bool Writable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> has a member attribute.
/// </summary>
/// <value><c>true</c> if has a member attribute; otherwise, <c>false</c>.</value>
public bool HasMemberAttribute { get; set; }
/// <summary>
/// Gets the default value.
/// </summary>
/// <value>The default value.</value>
public object DefaultValue
{
get
{
if (!_hasExplicitDefaultValue)
{
return null;
}
return _defaultValue;
}
set
{
_hasExplicitDefaultValue = true;
_defaultValue = value;
}
}
internal object GetResolvedDefaultValue()
{
if (_propertyType == null)
{
return null;
}
if (!_hasExplicitDefaultValue && !_hasGeneratedDefaultValue)
{
_defaultValue = ReflectionUtils.GetDefaultValue(PropertyType);
_hasGeneratedDefaultValue = true;
}
return _defaultValue;
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is required.
/// </summary>
/// <value>A value indicating whether this <see cref="JsonProperty"/> is required.</value>
public Required Required
{
get { return _required ?? Required.Default; }
set { _required = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this property preserves object references.
/// </summary>
/// <value>
/// <c>true</c> if this instance is reference; otherwise, <c>false</c>.
/// </value>
public bool? IsReference { get; set; }
/// <summary>
/// Gets or sets the property null value handling.
/// </summary>
/// <value>The null value handling.</value>
public NullValueHandling? NullValueHandling { get; set; }
/// <summary>
/// Gets or sets the property default value handling.
/// </summary>
/// <value>The default value handling.</value>
public DefaultValueHandling? DefaultValueHandling { get; set; }
/// <summary>
/// Gets or sets the property reference loop handling.
/// </summary>
/// <value>The reference loop handling.</value>
public ReferenceLoopHandling? ReferenceLoopHandling { get; set; }
/// <summary>
/// Gets or sets the property object creation handling.
/// </summary>
/// <value>The object creation handling.</value>
public ObjectCreationHandling? ObjectCreationHandling { get; set; }
/// <summary>
/// Gets or sets or sets the type name handling.
/// </summary>
/// <value>The type name handling.</value>
public TypeNameHandling? TypeNameHandling { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be serialize.
/// </summary>
/// <value>A predicate used to determine whether the property should be serialize.</value>
public Predicate<object> ShouldSerialize { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be deserialized.
/// </summary>
/// <value>A predicate used to determine whether the property should be deserialized.</value>
public Predicate<object> ShouldDeserialize { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be serialized.
/// </summary>
/// <value>A predicate used to determine whether the property should be serialized.</value>
public Predicate<object> GetIsSpecified { get; set; }
/// <summary>
/// Gets or sets an action used to set whether the property has been deserialized.
/// </summary>
/// <value>An action used to set whether the property has been deserialized.</value>
public Action<object, object> SetIsSpecified { get; set; }
/// <summary>
/// Returns a <see cref="String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
public override string ToString()
{
return PropertyName;
}
/// <summary>
/// Gets or sets the converter used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items converter.</value>
public JsonConverter ItemConverter { get; set; }
/// <summary>
/// Gets or sets whether this property's collection items are serialized as a reference.
/// </summary>
/// <value>Whether this property's collection items are serialized as a reference.</value>
public bool? ItemIsReference { get; set; }
/// <summary>
/// Gets or sets the the type name handling used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items type name handling.</value>
public TypeNameHandling? ItemTypeNameHandling { get; set; }
/// <summary>
/// Gets or sets the the reference loop handling used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items reference loop handling.</value>
public ReferenceLoopHandling? ItemReferenceLoopHandling { get; set; }
internal void WritePropertyName(JsonWriter writer)
{
if (_skipPropertyNameEscape)
{
writer.WritePropertyName(PropertyName, false);
}
else
{
writer.WritePropertyName(PropertyName);
}
}
}
}

View File

@@ -0,0 +1,180 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// A collection of <see cref="JsonProperty"/> objects.
/// </summary>
public class JsonPropertyCollection : KeyedCollection<string, JsonProperty>
{
private readonly Type _type;
private readonly List<JsonProperty> _list;
/// <summary>
/// Initializes a new instance of the <see cref="JsonPropertyCollection"/> class.
/// </summary>
/// <param name="type">The type.</param>
public JsonPropertyCollection(Type type)
: base(StringComparer.Ordinal)
{
ValidationUtils.ArgumentNotNull(type, "type");
_type = type;
// foreach over List<T> to avoid boxing the Enumerator
_list = (List<JsonProperty>)Items;
}
/// <summary>
/// When implemented in a derived class, extracts the key from the specified element.
/// </summary>
/// <param name="item">The element from which to extract the key.</param>
/// <returns>The key for the specified element.</returns>
protected override string GetKeyForItem(JsonProperty item)
{
return item.PropertyName;
}
/// <summary>
/// Adds a <see cref="JsonProperty"/> object.
/// </summary>
/// <param name="property">The property to add to the collection.</param>
public void AddProperty(JsonProperty property)
{
if (Contains(property.PropertyName))
{
// don't overwrite existing property with ignored property
if (property.Ignored)
{
return;
}
JsonProperty existingProperty = this[property.PropertyName];
bool duplicateProperty = true;
if (existingProperty.Ignored)
{
// remove ignored property so it can be replaced in collection
Remove(existingProperty);
duplicateProperty = false;
}
else
{
if (property.DeclaringType != null && existingProperty.DeclaringType != null)
{
if (property.DeclaringType.IsSubclassOf(existingProperty.DeclaringType)
|| (existingProperty.DeclaringType.IsInterface() && property.DeclaringType.ImplementInterface(existingProperty.DeclaringType)))
{
// current property is on a derived class and hides the existing
Remove(existingProperty);
duplicateProperty = false;
}
if (existingProperty.DeclaringType.IsSubclassOf(property.DeclaringType)
|| (property.DeclaringType.IsInterface() && existingProperty.DeclaringType.ImplementInterface(property.DeclaringType)))
{
// current property is hidden by the existing so don't add it
return;
}
}
}
if (duplicateProperty)
{
throw new JsonSerializationException("A member with the name '{0}' already exists on '{1}'. Use the JsonPropertyAttribute to specify another name.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, _type));
}
}
Add(property);
}
/// <summary>
/// Gets the closest matching <see cref="JsonProperty"/> object.
/// First attempts to get an exact case match of propertyName and then
/// a case insensitive match.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <returns>A matching property if found.</returns>
public JsonProperty GetClosestMatchProperty(string propertyName)
{
JsonProperty property = GetProperty(propertyName, StringComparison.Ordinal);
if (property == null)
{
property = GetProperty(propertyName, StringComparison.OrdinalIgnoreCase);
}
return property;
}
private bool TryGetValue(string key, out JsonProperty item)
{
if (Dictionary == null)
{
item = default(JsonProperty);
return false;
}
return Dictionary.TryGetValue(key, out item);
}
/// <summary>
/// Gets a property by property name.
/// </summary>
/// <param name="propertyName">The name of the property to get.</param>
/// <param name="comparisonType">Type property name string comparison.</param>
/// <returns>A matching property if found.</returns>
public JsonProperty GetProperty(string propertyName, StringComparison comparisonType)
{
// KeyedCollection has an ordinal comparer
if (comparisonType == StringComparison.Ordinal)
{
JsonProperty property;
if (TryGetValue(propertyName, out property))
{
return property;
}
return null;
}
for (int i = 0; i < _list.Count; i++)
{
JsonProperty property = _list[i];
if (string.Equals(propertyName, property.PropertyName, comparisonType))
{
return property;
}
}
return null;
}
}
}

View File

@@ -0,0 +1,149 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization
{
internal abstract class JsonSerializerInternalBase
{
private class ReferenceEqualsEqualityComparer : IEqualityComparer<object>
{
bool IEqualityComparer<object>.Equals(object x, object y)
{
return ReferenceEquals(x, y);
}
int IEqualityComparer<object>.GetHashCode(object obj)
{
// put objects in a bucket based on their reference
return RuntimeHelpers.GetHashCode(obj);
}
}
private ErrorContext _currentErrorContext;
private BidirectionalDictionary<string, object> _mappings;
internal readonly JsonSerializer Serializer;
internal readonly ITraceWriter TraceWriter;
protected JsonSerializerProxy InternalSerializer;
protected JsonSerializerInternalBase(JsonSerializer serializer)
{
ValidationUtils.ArgumentNotNull(serializer, nameof(serializer));
Serializer = serializer;
TraceWriter = serializer.TraceWriter;
}
internal BidirectionalDictionary<string, object> DefaultReferenceMappings
{
get
{
// override equality comparer for object key dictionary
// object will be modified as it deserializes and might have mutable hashcode
if (_mappings == null)
{
_mappings = new BidirectionalDictionary<string, object>(
EqualityComparer<string>.Default,
new ReferenceEqualsEqualityComparer(),
"A different value already has the Id '{0}'.",
"A different Id has already been assigned for value '{0}'.");
}
return _mappings;
}
}
private ErrorContext GetErrorContext(object currentObject, object member, string path, Exception error)
{
if (_currentErrorContext == null)
{
_currentErrorContext = new ErrorContext(currentObject, member, path, error);
}
if (_currentErrorContext.Error != error)
{
throw new InvalidOperationException("Current error context error is different to requested error.");
}
return _currentErrorContext;
}
protected void ClearErrorContext()
{
if (_currentErrorContext == null)
{
throw new InvalidOperationException("Could not clear error context. Error context is already null.");
}
_currentErrorContext = null;
}
protected bool IsErrorHandled(object currentObject, JsonContract contract, object keyValue, IJsonLineInfo lineInfo, string path, Exception ex)
{
ErrorContext errorContext = GetErrorContext(currentObject, keyValue, path, ex);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Error && !errorContext.Traced)
{
// only write error once
errorContext.Traced = true;
// kind of a hack but meh. might clean this up later
string message = (GetType() == typeof(JsonSerializerInternalWriter)) ? "Error serializing" : "Error deserializing";
if (contract != null)
{
message += " " + contract.UnderlyingType;
}
message += ". " + ex.Message;
// add line information to non-json.net exception message
if (!(ex is JsonException))
{
message = JsonPosition.FormatMessage(lineInfo, path, message);
}
TraceWriter.Trace(TraceLevel.Error, message, ex);
}
// attribute method is non-static so don't invoke if no object
if (contract != null && currentObject != null)
{
contract.InvokeOnError(currentObject, Serializer.Context, errorContext);
}
if (!errorContext.Handled)
{
Serializer.OnError(new ErrorEventArgs(currentObject, errorContext));
}
return errorContext.Handled;
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,278 @@
#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.Globalization;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
namespace Newtonsoft.Json.Serialization
{
internal class JsonSerializerProxy : JsonSerializer
{
private readonly JsonSerializerInternalReader _serializerReader;
private readonly JsonSerializerInternalWriter _serializerWriter;
private readonly JsonSerializer _serializer;
public override event EventHandler<ErrorEventArgs> Error
{
add { _serializer.Error += value; }
remove { _serializer.Error -= value; }
}
public override IReferenceResolver ReferenceResolver
{
get { return _serializer.ReferenceResolver; }
set { _serializer.ReferenceResolver = value; }
}
public override ITraceWriter TraceWriter
{
get { return _serializer.TraceWriter; }
set { _serializer.TraceWriter = value; }
}
public override IEqualityComparer EqualityComparer
{
get { return _serializer.EqualityComparer; }
set { _serializer.EqualityComparer = value; }
}
public override JsonConverterCollection Converters
{
get { return _serializer.Converters; }
}
public override DefaultValueHandling DefaultValueHandling
{
get { return _serializer.DefaultValueHandling; }
set { _serializer.DefaultValueHandling = value; }
}
public override IContractResolver ContractResolver
{
get { return _serializer.ContractResolver; }
set { _serializer.ContractResolver = value; }
}
public override MissingMemberHandling MissingMemberHandling
{
get { return _serializer.MissingMemberHandling; }
set { _serializer.MissingMemberHandling = value; }
}
public override NullValueHandling NullValueHandling
{
get { return _serializer.NullValueHandling; }
set { _serializer.NullValueHandling = value; }
}
public override ObjectCreationHandling ObjectCreationHandling
{
get { return _serializer.ObjectCreationHandling; }
set { _serializer.ObjectCreationHandling = value; }
}
public override ReferenceLoopHandling ReferenceLoopHandling
{
get { return _serializer.ReferenceLoopHandling; }
set { _serializer.ReferenceLoopHandling = value; }
}
public override PreserveReferencesHandling PreserveReferencesHandling
{
get { return _serializer.PreserveReferencesHandling; }
set { _serializer.PreserveReferencesHandling = value; }
}
public override TypeNameHandling TypeNameHandling
{
get { return _serializer.TypeNameHandling; }
set { _serializer.TypeNameHandling = value; }
}
public override MetadataPropertyHandling MetadataPropertyHandling
{
get { return _serializer.MetadataPropertyHandling; }
set { _serializer.MetadataPropertyHandling = value; }
}
public override FormatterAssemblyStyle TypeNameAssemblyFormat
{
get { return _serializer.TypeNameAssemblyFormat; }
set { _serializer.TypeNameAssemblyFormat = value; }
}
public override ConstructorHandling ConstructorHandling
{
get { return _serializer.ConstructorHandling; }
set { _serializer.ConstructorHandling = value; }
}
public override SerializationBinder Binder
{
get { return _serializer.Binder; }
set { _serializer.Binder = value; }
}
public override StreamingContext Context
{
get { return _serializer.Context; }
set { _serializer.Context = value; }
}
public override Formatting Formatting
{
get { return _serializer.Formatting; }
set { _serializer.Formatting = value; }
}
public override DateFormatHandling DateFormatHandling
{
get { return _serializer.DateFormatHandling; }
set { _serializer.DateFormatHandling = value; }
}
public override DateTimeZoneHandling DateTimeZoneHandling
{
get { return _serializer.DateTimeZoneHandling; }
set { _serializer.DateTimeZoneHandling = value; }
}
public override DateParseHandling DateParseHandling
{
get { return _serializer.DateParseHandling; }
set { _serializer.DateParseHandling = value; }
}
public override FloatFormatHandling FloatFormatHandling
{
get { return _serializer.FloatFormatHandling; }
set { _serializer.FloatFormatHandling = value; }
}
public override FloatParseHandling FloatParseHandling
{
get { return _serializer.FloatParseHandling; }
set { _serializer.FloatParseHandling = value; }
}
public override StringEscapeHandling StringEscapeHandling
{
get { return _serializer.StringEscapeHandling; }
set { _serializer.StringEscapeHandling = value; }
}
public override string DateFormatString
{
get { return _serializer.DateFormatString; }
set { _serializer.DateFormatString = value; }
}
public override CultureInfo Culture
{
get { return _serializer.Culture; }
set { _serializer.Culture = value; }
}
public override int? MaxDepth
{
get { return _serializer.MaxDepth; }
set { _serializer.MaxDepth = value; }
}
public override bool CheckAdditionalContent
{
get { return _serializer.CheckAdditionalContent; }
set { _serializer.CheckAdditionalContent = value; }
}
internal JsonSerializerInternalBase GetInternalSerializer()
{
if (_serializerReader != null)
{
return _serializerReader;
}
else
{
return _serializerWriter;
}
}
public JsonSerializerProxy(JsonSerializerInternalReader serializerReader)
{
ValidationUtils.ArgumentNotNull(serializerReader, nameof(serializerReader));
_serializerReader = serializerReader;
_serializer = serializerReader.Serializer;
}
public JsonSerializerProxy(JsonSerializerInternalWriter serializerWriter)
{
ValidationUtils.ArgumentNotNull(serializerWriter, nameof(serializerWriter));
_serializerWriter = serializerWriter;
_serializer = serializerWriter.Serializer;
}
internal override object DeserializeInternal(JsonReader reader, Type objectType)
{
if (_serializerReader != null)
{
return _serializerReader.Deserialize(reader, objectType, false);
}
else
{
return _serializer.Deserialize(reader, objectType);
}
}
internal override void PopulateInternal(JsonReader reader, object target)
{
if (_serializerReader != null)
{
_serializerReader.Populate(reader, target);
}
else
{
_serializer.Populate(reader, target);
}
}
internal override void SerializeInternal(JsonWriter jsonWriter, object value, Type rootType)
{
if (_serializerWriter != null)
{
_serializerWriter.Serialize(jsonWriter, value, rootType);
}
else
{
_serializer.Serialize(jsonWriter, value);
}
}
}
}

View File

@@ -0,0 +1,45 @@
#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;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>.
/// </summary>
public class JsonStringContract : JsonPrimitiveContract
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonStringContract"/> class.
/// </summary>
/// <param name="underlyingType">The underlying type for the contract.</param>
public JsonStringContract(Type underlyingType)
: base(underlyingType)
{
ContractType = JsonContractType.String;
}
}
}

View File

@@ -0,0 +1,461 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Security;
#if !(DOTNET || PORTABLE || PORTABLE40)
using System.Security.Permissions;
#endif
using Newtonsoft.Json.Utilities;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using System.Runtime.Serialization;
namespace Newtonsoft.Json.Serialization
{
internal static class JsonTypeReflector
{
private static bool? _dynamicCodeGeneration;
private static bool? _fullyTrusted;
public const string IdPropertyName = "$id";
public const string RefPropertyName = "$ref";
public const string TypePropertyName = "$type";
public const string ValuePropertyName = "$value";
public const string ArrayValuesPropertyName = "$values";
public const string ShouldSerializePrefix = "ShouldSerialize";
public const string SpecifiedPostfix = "Specified";
private static readonly ThreadSafeStore<Type, Func<object[], JsonConverter>> JsonConverterCreatorCache =
new ThreadSafeStore<Type, Func<object[], JsonConverter>>(GetJsonConverterCreator);
#if !(NET20 || DOTNET)
private static readonly ThreadSafeStore<Type, Type> AssociatedMetadataTypesCache = new ThreadSafeStore<Type, Type>(GetAssociateMetadataTypeFromAttribute);
private static ReflectionObject _metadataTypeAttributeReflectionObject;
#endif
public static T GetCachedAttribute<T>(object attributeProvider) where T : Attribute
{
return CachedAttributeGetter<T>.GetAttribute(attributeProvider);
}
#if !NET20
public static DataContractAttribute GetDataContractAttribute(Type type)
{
// DataContractAttribute does not have inheritance
Type currentType = type;
while (currentType != null)
{
DataContractAttribute result = CachedAttributeGetter<DataContractAttribute>.GetAttribute(currentType);
if (result != null)
{
return result;
}
currentType = currentType.BaseType();
}
return null;
}
public static DataMemberAttribute GetDataMemberAttribute(MemberInfo memberInfo)
{
// DataMemberAttribute does not have inheritance
// can't override a field
if (memberInfo.MemberType() == MemberTypes.Field)
{
return CachedAttributeGetter<DataMemberAttribute>.GetAttribute(memberInfo);
}
// search property and then search base properties if nothing is returned and the property is virtual
PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
DataMemberAttribute result = CachedAttributeGetter<DataMemberAttribute>.GetAttribute(propertyInfo);
if (result == null)
{
if (propertyInfo.IsVirtual())
{
Type currentType = propertyInfo.DeclaringType;
while (result == null && currentType != null)
{
PropertyInfo baseProperty = (PropertyInfo)ReflectionUtils.GetMemberInfoFromType(currentType, propertyInfo);
if (baseProperty != null && baseProperty.IsVirtual())
{
result = CachedAttributeGetter<DataMemberAttribute>.GetAttribute(baseProperty);
}
currentType = currentType.BaseType();
}
}
}
return result;
}
#endif
public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute)
{
JsonObjectAttribute objectAttribute = GetCachedAttribute<JsonObjectAttribute>(objectType);
if (objectAttribute != null)
{
return objectAttribute.MemberSerialization;
}
#if !NET20
DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType);
if (dataContractAttribute != null)
{
return MemberSerialization.OptIn;
}
#endif
#if !(DOTNET || PORTABLE40 || PORTABLE)
if (!ignoreSerializableAttribute)
{
SerializableAttribute serializableAttribute = GetCachedAttribute<SerializableAttribute>(objectType);
if (serializableAttribute != null)
{
return MemberSerialization.Fields;
}
}
#endif
// the default
return MemberSerialization.OptOut;
}
public static JsonConverter GetJsonConverter(object attributeProvider)
{
JsonConverterAttribute converterAttribute = GetCachedAttribute<JsonConverterAttribute>(attributeProvider);
if (converterAttribute != null)
{
Func<object[], JsonConverter> creator = JsonConverterCreatorCache.Get(converterAttribute.ConverterType);
if (creator != null)
{
return creator(converterAttribute.ConverterParameters);
}
}
return null;
}
/// <summary>
/// Lookup and create an instance of the JsonConverter type described by the argument.
/// </summary>
/// <param name="converterType">The JsonConverter type to create.</param>
/// <param name="converterArgs">Optional arguments to pass to an initializing constructor of the JsonConverter.
/// If null, the default constructor is used.</param>
public static JsonConverter CreateJsonConverterInstance(Type converterType, object[] converterArgs)
{
Func<object[], JsonConverter> converterCreator = JsonConverterCreatorCache.Get(converterType);
return converterCreator(converterArgs);
}
/// <summary>
/// Create a factory function that can be used to create instances of a JsonConverter described by the
/// argument type. The returned function can then be used to either invoke the converter's default ctor, or any
/// parameterized constructors by way of an object array.
/// </summary>
private static Func<object[], JsonConverter> GetJsonConverterCreator(Type converterType)
{
Func<object> defaultConstructor = (ReflectionUtils.HasDefaultConstructor(converterType, false))
? ReflectionDelegateFactory.CreateDefaultConstructor<object>(converterType)
: null;
return (parameters) =>
{
try
{
if (parameters != null)
{
ObjectConstructor<object> parameterizedConstructor = null;
Type[] paramTypes = parameters.Select(param => param.GetType()).ToArray();
ConstructorInfo parameterizedConstructorInfo = converterType.GetConstructor(paramTypes);
if (null != parameterizedConstructorInfo)
{
parameterizedConstructor = ReflectionDelegateFactory.CreateParameterizedConstructor(parameterizedConstructorInfo);
return (JsonConverter)parameterizedConstructor(parameters);
}
else
{
throw new JsonException("No matching parameterized constructor found for '{0}'.".FormatWith(CultureInfo.InvariantCulture, converterType));
}
}
if (defaultConstructor == null)
{
throw new JsonException("No parameterless constructor defined for '{0}'.".FormatWith(CultureInfo.InvariantCulture, converterType));
}
return (JsonConverter)defaultConstructor();
}
catch (Exception ex)
{
throw new JsonException("Error creating '{0}'.".FormatWith(CultureInfo.InvariantCulture, converterType), ex);
}
};
}
#if !(PORTABLE40 || PORTABLE)
public static TypeConverter GetTypeConverter(Type type)
{
return TypeDescriptor.GetConverter(type);
}
#endif
#if !(NET20 || DOTNET)
private static Type GetAssociatedMetadataType(Type type)
{
return AssociatedMetadataTypesCache.Get(type);
}
private static Type GetAssociateMetadataTypeFromAttribute(Type type)
{
Attribute[] customAttributes = ReflectionUtils.GetAttributes(type, null, true);
foreach (Attribute attribute in customAttributes)
{
Type attributeType = attribute.GetType();
// only test on attribute type name
// attribute assembly could change because of type forwarding, etc
if (string.Equals(attributeType.FullName, "System.ComponentModel.DataAnnotations.MetadataTypeAttribute", StringComparison.Ordinal))
{
const string metadataClassTypeName = "MetadataClassType";
if (_metadataTypeAttributeReflectionObject == null)
{
_metadataTypeAttributeReflectionObject = ReflectionObject.Create(attributeType, metadataClassTypeName);
}
return (Type)_metadataTypeAttributeReflectionObject.GetValue(attribute, metadataClassTypeName);
}
}
return null;
}
#endif
private static T GetAttribute<T>(Type type) where T : Attribute
{
T attribute;
#if !(NET20 || DOTNET)
Type metadataType = GetAssociatedMetadataType(type);
if (metadataType != null)
{
attribute = ReflectionUtils.GetAttribute<T>(metadataType, true);
if (attribute != null)
{
return attribute;
}
}
#endif
attribute = ReflectionUtils.GetAttribute<T>(type, true);
if (attribute != null)
{
return attribute;
}
foreach (Type typeInterface in type.GetInterfaces())
{
attribute = ReflectionUtils.GetAttribute<T>(typeInterface, true);
if (attribute != null)
{
return attribute;
}
}
return null;
}
private static T GetAttribute<T>(MemberInfo memberInfo) where T : Attribute
{
T attribute;
#if !(NET20 || DOTNET)
Type metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType);
if (metadataType != null)
{
MemberInfo metadataTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(metadataType, memberInfo);
if (metadataTypeMemberInfo != null)
{
attribute = ReflectionUtils.GetAttribute<T>(metadataTypeMemberInfo, true);
if (attribute != null)
{
return attribute;
}
}
}
#endif
attribute = ReflectionUtils.GetAttribute<T>(memberInfo, true);
if (attribute != null)
{
return attribute;
}
if (memberInfo.DeclaringType != null)
{
foreach (Type typeInterface in memberInfo.DeclaringType.GetInterfaces())
{
MemberInfo interfaceTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(typeInterface, memberInfo);
if (interfaceTypeMemberInfo != null)
{
attribute = ReflectionUtils.GetAttribute<T>(interfaceTypeMemberInfo, true);
if (attribute != null)
{
return attribute;
}
}
}
}
return null;
}
public static T GetAttribute<T>(object provider) where T : Attribute
{
Type type = provider as Type;
if (type != null)
{
return GetAttribute<T>(type);
}
MemberInfo memberInfo = provider as MemberInfo;
if (memberInfo != null)
{
return GetAttribute<T>(memberInfo);
}
return ReflectionUtils.GetAttribute<T>(provider, true);
}
#if DEBUG
internal static void SetFullyTrusted(bool fullyTrusted)
{
_fullyTrusted = fullyTrusted;
}
internal static void SetDynamicCodeGeneration(bool dynamicCodeGeneration)
{
_dynamicCodeGeneration = dynamicCodeGeneration;
}
#endif
public static bool DynamicCodeGeneration
{
#if !(NET20 || NET35 || PORTABLE)
[SecuritySafeCritical]
#endif
get
{
if (_dynamicCodeGeneration == null)
{
#if !(DOTNET || PORTABLE40 || PORTABLE)
try
{
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess).Demand();
new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand();
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
new SecurityPermission(PermissionState.Unrestricted).Demand();
_dynamicCodeGeneration = true;
}
catch (Exception)
{
_dynamicCodeGeneration = false;
}
#else
_dynamicCodeGeneration = false;
#endif
}
return _dynamicCodeGeneration.GetValueOrDefault();
}
}
public static bool FullyTrusted
{
get
{
if (_fullyTrusted == null)
{
#if (DOTNET || PORTABLE || PORTABLE40)
_fullyTrusted = false;
#elif !(NET20 || NET35 || PORTABLE40)
AppDomain appDomain = AppDomain.CurrentDomain;
_fullyTrusted = appDomain.IsHomogenous && appDomain.IsFullyTrusted;
#else
try
{
new SecurityPermission(PermissionState.Unrestricted).Demand();
_fullyTrusted = true;
}
catch (Exception)
{
_fullyTrusted = false;
}
#endif
}
return _fullyTrusted.GetValueOrDefault();
}
}
public static ReflectionDelegateFactory ReflectionDelegateFactory
{
get
{
#if !(PORTABLE40 || PORTABLE || DOTNET)
if (DynamicCodeGeneration)
{
return DynamicReflectionDelegateFactory.Instance;
}
return LateBoundReflectionDelegateFactory.Instance;
#else
return ExpressionReflectionDelegateFactory.Instance;
#endif
}
}
}
}

View File

@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Represents a trace writer that writes to memory. When the trace message limit is
/// reached then old trace messages will be removed as new messages are added.
/// </summary>
public class MemoryTraceWriter : ITraceWriter
{
private readonly Queue<string> _traceMessages;
/// <summary>
/// Gets the <see cref="TraceLevel"/> that will be used to filter the trace messages passed to the writer.
/// For example a filter level of <code>Info</code> will exclude <code>Verbose</code> messages and include <code>Info</code>,
/// <code>Warning</code> and <code>Error</code> messages.
/// </summary>
/// <value>
/// The <see cref="TraceLevel"/> that will be used to filter the trace messages passed to the writer.
/// </value>
public TraceLevel LevelFilter { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MemoryTraceWriter"/> class.
/// </summary>
public MemoryTraceWriter()
{
LevelFilter = TraceLevel.Verbose;
_traceMessages = new Queue<string>();
}
/// <summary>
/// Writes the specified trace level, message and optional exception.
/// </summary>
/// <param name="level">The <see cref="TraceLevel"/> at which to write this trace.</param>
/// <param name="message">The trace message.</param>
/// <param name="ex">The trace exception. This parameter is optional.</param>
public void Trace(TraceLevel level, string message, Exception ex)
{
if (_traceMessages.Count >= 1000)
{
_traceMessages.Dequeue();
}
StringBuilder sb = new StringBuilder();
sb.Append(DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff", CultureInfo.InvariantCulture));
sb.Append(" ");
sb.Append(level.ToString("g"));
sb.Append(" ");
sb.Append(message);
_traceMessages.Enqueue(sb.ToString());
}
/// <summary>
/// Returns an enumeration of the most recent trace messages.
/// </summary>
/// <returns>An enumeration of the most recent trace messages.</returns>
public IEnumerable<string> GetTraceMessages()
{
return _traceMessages;
}
/// <summary>
/// Returns a <see cref="String"/> of the most recent trace messages.
/// </summary>
/// <returns>
/// A <see cref="String"/> of the most recent trace messages.
/// </returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (string traceMessage in _traceMessages)
{
if (sb.Length > 0)
{
sb.AppendLine();
}
sb.Append(traceMessage);
}
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,33 @@
#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
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Represents a method that constructs an object.
/// </summary>
/// <typeparam name="T">The object type to create.</typeparam>
public delegate object ObjectConstructor<T>(params object[] args);
}

View File

@@ -0,0 +1,37 @@
#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;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// When applied to a method, specifies that the method is called when an error occurs serializing an object.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class OnErrorAttribute : Attribute
{
}
}

View File

@@ -0,0 +1,71 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Reflection;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Provides methods to get attributes from a <see cref="System.Type"/>, <see cref="MemberInfo"/>, <see cref="ParameterInfo"/> or <see cref="Assembly"/>.
/// </summary>
public class ReflectionAttributeProvider : IAttributeProvider
{
private readonly object _attributeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="ReflectionAttributeProvider"/> class.
/// </summary>
/// <param name="attributeProvider">The instance to get attributes for. This parameter should be a <see cref="System.Type"/>, <see cref="MemberInfo"/>, <see cref="ParameterInfo"/> or <see cref="Assembly"/>.</param>
public ReflectionAttributeProvider(object attributeProvider)
{
ValidationUtils.ArgumentNotNull(attributeProvider, nameof(attributeProvider));
_attributeProvider = attributeProvider;
}
/// <summary>
/// Returns a collection of all of the attributes, or an empty collection if there are no attributes.
/// </summary>
/// <param name="inherit">When true, look up the hierarchy chain for the inherited custom attribute.</param>
/// <returns>A collection of <see cref="Attribute"/>s, or an empty collection.</returns>
public IList<Attribute> GetAttributes(bool inherit)
{
return ReflectionUtils.GetAttributes(_attributeProvider, null, inherit);
}
/// <summary>
/// Returns a collection of attributes, identified by type, or an empty collection if there are no attributes.
/// </summary>
/// <param name="attributeType">The type of the attributes.</param>
/// <param name="inherit">When true, look up the hierarchy chain for the inherited custom attribute.</param>
/// <returns>A collection of <see cref="Attribute"/>s, or an empty collection.</returns>
public IList<Attribute> GetAttributes(Type attributeType, bool inherit)
{
return ReflectionUtils.GetAttributes(_attributeProvider, attributeType, inherit);
}
}
}

View File

@@ -0,0 +1,84 @@
#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.Reflection;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Get and set values for a <see cref="MemberInfo"/> using reflection.
/// </summary>
public class ReflectionValueProvider : IValueProvider
{
private readonly MemberInfo _memberInfo;
/// <summary>
/// Initializes a new instance of the <see cref="ReflectionValueProvider"/> class.
/// </summary>
/// <param name="memberInfo">The member info.</param>
public ReflectionValueProvider(MemberInfo memberInfo)
{
ValidationUtils.ArgumentNotNull(memberInfo, nameof(memberInfo));
_memberInfo = memberInfo;
}
/// <summary>
/// Sets the value.
/// </summary>
/// <param name="target">The target to set the value on.</param>
/// <param name="value">The value to set on the target.</param>
public void SetValue(object target, object value)
{
try
{
ReflectionUtils.SetMemberValue(_memberInfo, target, value);
}
catch (Exception ex)
{
throw new JsonSerializationException("Error setting value to '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex);
}
}
/// <summary>
/// Gets the value.
/// </summary>
/// <param name="target">The target to get the value from.</param>
/// <returns>The value.</returns>
public object GetValue(object target)
{
try
{
return ReflectionUtils.GetMemberValue(_memberInfo, target);
}
catch (Exception ex)
{
throw new JsonSerializationException("Error getting value from '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex);
}
}
}
}

View File

@@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace Newtonsoft.Json.Serialization
{
internal class TraceJsonReader : JsonReader, IJsonLineInfo
{
private readonly JsonReader _innerReader;
private readonly JsonTextWriter _textWriter;
private readonly StringWriter _sw;
public TraceJsonReader(JsonReader innerReader)
{
_innerReader = innerReader;
_sw = new StringWriter(CultureInfo.InvariantCulture);
// prefix the message in the stringwriter to avoid concat with a potentially large JSON string
_sw.Write("Deserialized JSON: " + Environment.NewLine);
_textWriter = new JsonTextWriter(_sw);
_textWriter.Formatting = Formatting.Indented;
}
public string GetDeserializedJsonMessage()
{
return _sw.ToString();
}
public override bool Read()
{
var value = _innerReader.Read();
_textWriter.WriteToken(_innerReader, false, false, true);
return value;
}
public override int? ReadAsInt32()
{
var value = _innerReader.ReadAsInt32();
_textWriter.WriteToken(_innerReader, false, false, true);
return value;
}
public override string ReadAsString()
{
var value = _innerReader.ReadAsString();
_textWriter.WriteToken(_innerReader, false, false, true);
return value;
}
public override byte[] ReadAsBytes()
{
var value = _innerReader.ReadAsBytes();
_textWriter.WriteToken(_innerReader, false, false, true);
return value;
}
public override decimal? ReadAsDecimal()
{
var value = _innerReader.ReadAsDecimal();
_textWriter.WriteToken(_innerReader, false, false, true);
return value;
}
public override double? ReadAsDouble()
{
var value = _innerReader.ReadAsDouble();
_textWriter.WriteToken(_innerReader, false, false, true);
return value;
}
public override bool? ReadAsBoolean()
{
var value = _innerReader.ReadAsBoolean();
_textWriter.WriteToken(_innerReader, false, false, true);
return value;
}
public override DateTime? ReadAsDateTime()
{
var value = _innerReader.ReadAsDateTime();
_textWriter.WriteToken(_innerReader, false, false, true);
return value;
}
#if !NET20
public override DateTimeOffset? ReadAsDateTimeOffset()
{
var value = _innerReader.ReadAsDateTimeOffset();
_textWriter.WriteToken(_innerReader, false, false, true);
return value;
}
#endif
public override int Depth
{
get { return _innerReader.Depth; }
}
public override string Path
{
get { return _innerReader.Path; }
}
public override char QuoteChar
{
get { return _innerReader.QuoteChar; }
protected internal set { _innerReader.QuoteChar = value; }
}
public override JsonToken TokenType
{
get { return _innerReader.TokenType; }
}
public override object Value
{
get { return _innerReader.Value; }
}
public override Type ValueType
{
get { return _innerReader.ValueType; }
}
public override void Close()
{
_innerReader.Close();
}
bool IJsonLineInfo.HasLineInfo()
{
IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo;
return lineInfo != null && lineInfo.HasLineInfo();
}
int IJsonLineInfo.LineNumber
{
get
{
IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo;
return (lineInfo != null) ? lineInfo.LineNumber : 0;
}
}
int IJsonLineInfo.LinePosition
{
get
{
IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo;
return (lineInfo != null) ? lineInfo.LinePosition : 0;
}
}
}
}

View File

@@ -0,0 +1,322 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
using System.Numerics;
#endif
using System.Text;
namespace Newtonsoft.Json.Serialization
{
internal class TraceJsonWriter : JsonWriter
{
private readonly JsonWriter _innerWriter;
private readonly JsonTextWriter _textWriter;
private readonly StringWriter _sw;
public TraceJsonWriter(JsonWriter innerWriter)
{
_innerWriter = innerWriter;
_sw = new StringWriter(CultureInfo.InvariantCulture);
// prefix the message in the stringwriter to avoid concat with a potentially large JSON string
_sw.Write("Serialized JSON: " + Environment.NewLine);
_textWriter = new JsonTextWriter(_sw);
_textWriter.Formatting = Formatting.Indented;
_textWriter.Culture = innerWriter.Culture;
_textWriter.DateFormatHandling = innerWriter.DateFormatHandling;
_textWriter.DateFormatString = innerWriter.DateFormatString;
_textWriter.DateTimeZoneHandling = innerWriter.DateTimeZoneHandling;
_textWriter.FloatFormatHandling = innerWriter.FloatFormatHandling;
}
public string GetSerializedJsonMessage()
{
return _sw.ToString();
}
public override void WriteValue(decimal value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(bool value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(byte value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(byte? value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(char value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(byte[] value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(DateTime value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
#if !NET20
public override void WriteValue(DateTimeOffset value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
#endif
public override void WriteValue(double value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteUndefined()
{
_textWriter.WriteUndefined();
_innerWriter.WriteUndefined();
base.WriteUndefined();
}
public override void WriteNull()
{
_textWriter.WriteNull();
_innerWriter.WriteNull();
base.WriteUndefined();
}
public override void WriteValue(float value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(Guid value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(int value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(long value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(object value)
{
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
if (value is BigInteger)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
InternalWriteValue(JsonToken.Integer);
}
else
#endif
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
}
public override void WriteValue(sbyte value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(short value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(string value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(TimeSpan value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(uint value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(ulong value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(Uri value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteValue(ushort value)
{
_textWriter.WriteValue(value);
_innerWriter.WriteValue(value);
base.WriteValue(value);
}
public override void WriteWhitespace(string ws)
{
_textWriter.WriteWhitespace(ws);
_innerWriter.WriteWhitespace(ws);
base.WriteWhitespace(ws);
}
public override void WriteComment(string text)
{
_textWriter.WriteComment(text);
_innerWriter.WriteComment(text);
base.WriteComment(text);
}
public override void WriteStartArray()
{
_textWriter.WriteStartArray();
_innerWriter.WriteStartArray();
base.WriteStartArray();
}
public override void WriteEndArray()
{
_textWriter.WriteEndArray();
_innerWriter.WriteEndArray();
base.WriteEndArray();
}
public override void WriteStartConstructor(string name)
{
_textWriter.WriteStartConstructor(name);
_innerWriter.WriteStartConstructor(name);
base.WriteStartConstructor(name);
}
public override void WriteEndConstructor()
{
_textWriter.WriteEndConstructor();
_innerWriter.WriteEndConstructor();
base.WriteEndConstructor();
}
public override void WritePropertyName(string name)
{
_textWriter.WritePropertyName(name);
_innerWriter.WritePropertyName(name);
base.WritePropertyName(name);
}
public override void WritePropertyName(string name, bool escape)
{
_textWriter.WritePropertyName(name, escape);
_innerWriter.WritePropertyName(name, escape);
// method with escape will error
base.WritePropertyName(name);
}
public override void WriteStartObject()
{
_textWriter.WriteStartObject();
_innerWriter.WriteStartObject();
base.WriteStartObject();
}
public override void WriteEndObject()
{
_textWriter.WriteEndObject();
_innerWriter.WriteEndObject();
base.WriteEndObject();
}
public override void WriteRawValue(string json)
{
_textWriter.WriteRawValue(json);
_innerWriter.WriteRawValue(json);
// calling base method will write json twice
InternalWriteValue(JsonToken.Undefined);
}
public override void WriteRaw(string json)
{
_textWriter.WriteRaw(json);
_innerWriter.WriteRaw(json);
base.WriteRaw(json);
}
public override void Close()
{
_textWriter.Close();
_innerWriter.Close();
base.Close();
}
public override void Flush()
{
_textWriter.Flush();
_innerWriter.Flush();
}
}
}