Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@ -0,0 +1,79 @@
2009-08-18 Marek Habersack <mhabersack@novell.com>
* JavaScriptSerializer.cs: read converters from the config only if
explicitly requested.
2009-08-17 Marek Habersack <mhabersack@novell.com>
* JsonSerializer.cs: serialize fields before properties.
* JavaScriptSerializer.cs: MaxJsonLength default value for .NET
3.5 is 2097152
2009-03-17 Marek Habersack <mhabersack@novell.com>
* JavaScriptSerializer.cs: if conversion of IDictionary or
IDictionary <K,V> to an object is requested, make sure that a
concrete type is used (in both cases Dictionary <string, object>).
Make sure that if the target type is an IDictionary<K,V> that the
key is either an object or a string.
2009-03-06 Marek Habersack <mhabersack@novell.com>
* JsonDeserializer.cs: unquoted key values must ignore leading
and trailing whitespace
2008-12-05 Marek Habersack <mhabersack@novell.com>
* JsonSerializer.cs: StringBuilder extension methods aren't used
anymore, changed to calls to static methods in
StringBuilderExtensions.
* StringBuilderExtensions.cs: cannot use extension methods here
because this file is also used in the version 1.0 build which
doesn't reference System.Core
2008-10-22 Marek Habersack <mhabersack@novell.com>
* JsonDeserializer.cs: object can contain more than one unquoted
keys.
2008-09-23 Marek Habersack <mhabersack@novell.com>
* JavaScriptSerializer.cs: removed the LazyDictionary class, it's
not needed anymore.
2008-09-23 Juraj Skripsky <js@hotfeet.ch>
* JsonSerializer.cs: "SerializeGenericDictionary" is an instance method,
fix retrieval of its MethodInfo.
Initialize serializeGenericDictionaryMethods (lazily).
Add and use GetClosedIDictionaryBase to also handle cases where a
non-generic class implements a closed IDictionary<,> (e.g.
SomeDictionary : IDictionary<string, object>). Fixes bug #424704.
First check for IDictionary<,>, then for IDictionary.
2008-09-20 Marek Habersack <mhabersack@novell.com>
* JsonDeserializer.cs: added support for stand-alone NaN, Infinity
and -Infinity values, as well as the same within an array.
2008-09-19 Marek Habersack <mhabersack@novell.com>
* Json.cs: added new Serialize overload which takes a TextWriter
for its output parameter.
Added Deserialize methods.
* JsonSerializer.cs: made InitialJavaScriptDateTicks internal.
Added new Serialize overload which takes a TextWriter for its
output parameter.
Added WriteValue overloads for float and double - they must not be
converted to strings as IConvertibles because their Max/MinValue
end up converted incorrectly.
* JavaScriptSerializer.cs: adjustments for the new JSON
(de)serializer.
* JsonDeserializer.cs: new JSON deserializer code, fully compliant
with the .NET AJAX one.

View File

@ -0,0 +1,28 @@
2008-08-28 Marek Habersack <mhabersack@novell.com>
* JsonSerializer.cs: each value stored in an enumerable is treated
as a top-level object.
2008-08-22 Marek Habersack <mhabersack@novell.com>
* JsonSerializer.cs: do not perform deep object serialization - it
results in all kinds of problems (including too big size of the
resulting string, recursion errors when two or more objects in the
hierarchy hold a reference to some object) and is not what .NET
code does.
Property name is written only after it is determined if we're
serializing the property or not.
Entire object is serialized only if it's the object requested for
serialization by calling code.
2008-08-19 Marek Habersack <mhabersack@novell.com>
* JsonSerializer.cs: implemented a work-around for a bug in the
SerializedLazyDictionary which would fail to serialize a type if
any of its properties would throw an exception.
2008-05-20 Jb Evain <jbevain@novell.com>
*.cs: all files from JSon.NET are now re-licensed under the
MIT/X11 license, thanks to his author James Newton-King
for relicensing them.

View File

@ -0,0 +1,121 @@
#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.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Collections.Generic;
using System.Drawing;
using System.Web.UI.WebControls;
namespace Newtonsoft.Json
{
internal static class JavaScriptUtils
{
public static void WriteEscapedJavaScriptString (string value, TextWriter writer) {
WriteEscapedJavaScriptString (value, '"', true, writer);
}
public static void WriteEscapedJavaScriptString (string value, char delimiter, bool appendDelimiters, TextWriter writer) {
// leading delimiter
if (appendDelimiters)
writer.Write (delimiter);
if (!string.IsNullOrEmpty (value))
for (int i = 0; i < value.Length; i++)
WriteJavaScriptChar (value [i], delimiter, writer);
// trailing delimiter
if (appendDelimiters)
writer.Write (delimiter);
}
public static void WriteEscapedJavaScriptChar (char value, char delimiter, bool appendDelimiters, TextWriter writer) {
// leading delimiter
if (appendDelimiters)
writer.Write (delimiter);
WriteJavaScriptChar (value, delimiter, writer);
// trailing delimiter
if (appendDelimiters)
writer.Write (delimiter);
}
public static void WriteJavaScriptChar (char value, char delimiter, TextWriter writer) {
switch (value) {
case '\t':
writer.Write (@"\t");
break;
case '\n':
writer.Write (@"\n");
break;
case '\r':
writer.Write (@"\r");
break;
case '\f':
writer.Write (@"\f");
break;
case '\b':
writer.Write (@"\b");
break;
case '<':
writer.Write (@"\u003c");
break;
case '>':
writer.Write (@"\u003e");
break;
case '"':
// only escape if this charater is being used as the delimiter
if (delimiter == '"')
writer.Write (@"\""");
else
writer.Write (value);
break;
case '\'':
writer.Write (@"\u0027");
break;
case '\\':
writer.Write (@"\\");
break;
default:
if (value > '\u001f')
writer.Write (value);
else {
writer.Write("\\u00");
int intVal = (int) value;
writer.Write ((char) ('0' + (intVal >> 4)));
intVal &= 0xf;
writer.Write ((char) (intVal < 10 ? '0' + intVal : 'a' + (intVal - 10)));
}
break;
}
}
}
}

View File

@ -0,0 +1,291 @@
#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.Reflection;
using System.Collections;
using System.ComponentModel;
namespace Newtonsoft.Json.Utilities
{
internal static class ReflectionUtils
{
public static bool IsInstantiatableType(Type t)
{
if (t == null)
throw new ArgumentNullException("t");
if (t.IsAbstract || t.IsInterface || t.IsArray)
return false;
if (!HasDefaultConstructor(t))
return false;
return true;
}
public static bool HasDefaultConstructor(Type t)
{
if (t == null)
throw new ArgumentNullException("t");
return (t.GetConstructor(BindingFlags.Instance, null, Type.EmptyTypes, null) != null);
}
public static bool IsAssignable (Type to, Type from) {
if (to == null)
throw new ArgumentNullException("to");
if (to.IsAssignableFrom (from))
return true;
if (to.IsGenericType && from.IsGenericTypeDefinition)
return to.IsAssignableFrom (from.MakeGenericType (to.GetGenericArguments ()));
return false;
}
public static bool IsSubClass(Type type, Type check)
{
if (type == null || check == null)
return false;
if (type == check)
return true;
if (check.IsInterface)
{
foreach (Type t in type.GetInterfaces())
{
if (IsSubClass(t, check)) return true;
}
}
if (type.IsGenericType && !type.IsGenericTypeDefinition)
{
if (IsSubClass(type.GetGenericTypeDefinition(), check))
return true;
}
return IsSubClass(type.BaseType, check);
}
/// <summary>
/// Gets the type of the typed list's items.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The type of the typed list's items.</returns>
public static Type GetTypedListItemType(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
if (type.IsArray)
return type.GetElementType ();
else if (type.IsGenericType && typeof (List<>).IsAssignableFrom (type.GetGenericTypeDefinition ()))
return type.GetGenericArguments () [0];
else
throw new Exception ("Bad type");
}
public static Type GetTypedDictionaryValueType(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
Type genDictType = GetGenericDictionary(type);
if (genDictType != null)
return genDictType.GetGenericArguments () [1];
else if (typeof(IDictionary).IsAssignableFrom(type))
return null;
else
throw new Exception("Bad type");
}
static readonly Type GenericDictionaryType = typeof (IDictionary<,>);
public static Type GetGenericDictionary (Type type) {
if (type.IsGenericType && GenericDictionaryType.IsAssignableFrom (type.GetGenericTypeDefinition ()))
return type;
Type[] ifaces = type.GetInterfaces();
if (ifaces != null)
for (int i = 0; i < ifaces.Length; i++) {
Type current = GetGenericDictionary (ifaces [i]);
if (current != null)
return current;
}
return null;
}
public static Type GetMemberUnderlyingType(MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return ((FieldInfo)member).FieldType;
case MemberTypes.Property:
return ((PropertyInfo)member).PropertyType;
case MemberTypes.Event:
return ((EventInfo)member).EventHandlerType;
default:
throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", "member");
}
}
/// <summary>
/// Determines whether the member is an indexed property.
/// </summary>
/// <param name="member">The member.</param>
/// <returns>
/// <c>true</c> if the member is an indexed property; otherwise, <c>false</c>.
/// </returns>
public static bool IsIndexedProperty(MemberInfo member)
{
if (member == null)
throw new ArgumentNullException("member");
PropertyInfo propertyInfo = member as PropertyInfo;
if (propertyInfo != null)
return IsIndexedProperty(propertyInfo);
else
return false;
}
/// <summary>
/// Determines whether the property is an indexed property.
/// </summary>
/// <param name="property">The property.</param>
/// <returns>
/// <c>true</c> if the property is an indexed property; otherwise, <c>false</c>.
/// </returns>
public static bool IsIndexedProperty(PropertyInfo property)
{
if (property == null)
throw new ArgumentNullException("property");
return (property.GetIndexParameters().Length > 0);
}
/// <summary>
/// Gets the member's value on the object.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="target">The target object.</param>
/// <returns>The member's value on the object.</returns>
public static object GetMemberValue(MemberInfo member, object target)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return ((FieldInfo)member).GetValue(target);
case MemberTypes.Property:
try
{
return ((PropertyInfo)member).GetValue(target, null);
}
catch (TargetParameterCountException e)
{
throw new ArgumentException("MemberInfo has index parameters", "member", e);
}
default:
throw new ArgumentException("MemberInfo is not of type FieldInfo or PropertyInfo", "member");
}
}
/// <summary>
/// Sets the member's value on the target object.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="target">The target.</param>
/// <param name="value">The value.</param>
public static void SetMemberValue(MemberInfo member, object target, object value)
{
switch (member.MemberType)
{
case MemberTypes.Field:
((FieldInfo)member).SetValue(target, value);
break;
case MemberTypes.Property:
((PropertyInfo)member).SetValue(target, value, null);
break;
default:
throw new ArgumentException("MemberInfo must be if type FieldInfo or PropertyInfo", "member");
}
}
/// <summary>
/// Determines whether the specified MemberInfo can be read.
/// </summary>
/// <param name="member">The MemberInfo to determine whether can be read.</param>
/// <returns>
/// <c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>.
/// </returns>
public static bool CanReadMemberValue(MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return true;
case MemberTypes.Property:
return ((PropertyInfo) member).CanRead;
default:
return false;
}
}
/// <summary>
/// Determines whether the specified MemberInfo can be set.
/// </summary>
/// <param name="member">The MemberInfo to determine whether can be set.</param>
/// <returns>
/// <c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>.
/// </returns>
public static bool CanSetMemberValue(MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return true;
case MemberTypes.Property:
return ((PropertyInfo)member).CanWrite;
default:
return false;
}
}
public static IEnumerable<MemberInfo> GetFieldsAndProperties (Type type, BindingFlags bindingAttr) {
MemberInfo [] members = type.GetFields (bindingAttr);
for (int i = 0; i < members.Length; i++)
yield return members [i];
members = type.GetProperties (bindingAttr);
for (int i = 0; i < members.Length; i++)
yield return members [i];
}
}
}

View File

@ -0,0 +1,45 @@
//
// JavaScriptConverter.cs
//
// Author:
// Igor Zelmanovich <igorz@mainsoft.com>
//
// (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
//
//
// 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.
//
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Web.Script.Serialization
{
public abstract class JavaScriptConverter
{
protected JavaScriptConverter () { }
public abstract IEnumerable<Type> SupportedTypes { get; }
public abstract object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer);
public abstract IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer);
}
}

View File

@ -0,0 +1,443 @@
//
// JavaScriptSerializer.cs
//
// Authors:
// Konstantin Triger <kostat@mainsoft.com>
// Marek Safar <marek.safar@gmail.com>
//
// (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
// Copyright 2012 Xamarin Inc.
//
// 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.
//
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using System.Collections;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.ComponentModel;
using System.Configuration;
using System.Web.Configuration;
namespace System.Web.Script.Serialization
{
public class JavaScriptSerializer
{
internal const string SerializedTypeNameKey = "__type";
List<IEnumerable<JavaScriptConverter>> _converterList;
int _maxJsonLength;
int _recursionLimit;
JavaScriptTypeResolver _typeResolver;
internal static readonly JavaScriptSerializer DefaultSerializer = new JavaScriptSerializer (null, false);
public JavaScriptSerializer () : this (null, false)
{
}
public JavaScriptSerializer (JavaScriptTypeResolver resolver) : this (resolver, false)
{
}
internal JavaScriptSerializer (JavaScriptTypeResolver resolver, bool registerConverters)
{
_typeResolver = resolver;
ScriptingJsonSerializationSection section = (ScriptingJsonSerializationSection) ConfigurationManager.GetSection ("system.web.extensions/scripting/webServices/jsonSerialization");
if (section == null) {
#if NET_3_5
_maxJsonLength = 2097152;
#else
_maxJsonLength = 102400;
#endif
_recursionLimit = 100;
} else {
_maxJsonLength = section.MaxJsonLength;
_recursionLimit = section.RecursionLimit;
if (registerConverters) {
ConvertersCollection converters = section.Converters;
if (converters != null && converters.Count > 0) {
var cvtlist = new List <JavaScriptConverter> ();
Type type;
string typeName;
JavaScriptConverter jsc;
foreach (Converter cvt in converters) {
typeName = cvt != null ? cvt.Type : null;
if (typeName == null)
continue;
type = HttpApplication.LoadType (typeName, true);
if (type == null || !typeof (JavaScriptConverter).IsAssignableFrom (type))
continue;
jsc = Activator.CreateInstance (type) as JavaScriptConverter;
cvtlist.Add (jsc);
}
RegisterConverters (cvtlist);
}
}
}
}
public int MaxJsonLength {
get {
return _maxJsonLength;
}
set {
_maxJsonLength = value;
}
}
public int RecursionLimit {
get {
return _recursionLimit;
}
set {
_recursionLimit = value;
}
}
internal JavaScriptTypeResolver TypeResolver {
get { return _typeResolver; }
}
public T ConvertToType<T> (object obj) {
if (obj == null)
return default (T);
return (T) ConvertToType (obj, typeof (T));
}
#if NET_4_0
public
#else
internal
#endif
object ConvertToType (object obj, Type targetType)
{
if (obj == null)
return null;
if (obj is IDictionary<string, object>) {
if (targetType == null)
obj = EvaluateDictionary ((IDictionary<string, object>) obj);
else {
JavaScriptConverter converter = GetConverter (targetType);
if (converter != null)
return converter.Deserialize (
EvaluateDictionary ((IDictionary<string, object>) obj),
targetType, this);
}
return ConvertToObject ((IDictionary<string, object>) obj, targetType);
}
if (obj is ArrayList)
return ConvertToList ((ArrayList) obj, targetType);
if (targetType == null)
return obj;
Type sourceType = obj.GetType ();
if (targetType.IsAssignableFrom (sourceType))
return obj;
if (targetType.IsEnum)
if (obj is string)
return Enum.Parse (targetType, (string) obj, true);
else
return Enum.ToObject (targetType, obj);
TypeConverter c = TypeDescriptor.GetConverter (targetType);
if (c.CanConvertFrom (sourceType)) {
if (obj is string)
return c.ConvertFromInvariantString ((string) obj);
return c.ConvertFrom (obj);
}
/*
* Take care of the special case whereas in JSON an empty string ("") really means
* an empty value
* (see: https://bugzilla.novell.com/show_bug.cgi?id=328836)
*/
if ((targetType.IsGenericType) && (targetType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
string s = obj as String;
if (String.IsNullOrEmpty(s))
return null;
}
return Convert.ChangeType (obj, targetType);
}
public T Deserialize<T> (string input) {
return ConvertToType<T> (DeserializeObjectInternal(input));
}
static object Evaluate (object value) {
return Evaluate (value, false);
}
static object Evaluate (object value, bool convertListToArray) {
if (value is IDictionary<string, object>)
value = EvaluateDictionary ((IDictionary<string, object>) value, convertListToArray);
else if (value is ArrayList)
value = EvaluateList ((ArrayList) value, convertListToArray);
return value;
}
static object EvaluateList (ArrayList e) {
return EvaluateList (e, false);
}
static object EvaluateList (ArrayList e, bool convertListToArray) {
ArrayList list = new ArrayList ();
foreach (object value in e)
list.Add (Evaluate (value, convertListToArray));
return convertListToArray ? (object) list.ToArray () : list;
}
static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict) {
return EvaluateDictionary (dict, false);
}
static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict, bool convertListToArray) {
Dictionary<string, object> d = new Dictionary<string, object> (StringComparer.Ordinal);
foreach (KeyValuePair<string, object> entry in dict) {
d.Add (entry.Key, Evaluate (entry.Value, convertListToArray));
}
return d;
}
static readonly Type typeofObject = typeof(object);
static readonly Type typeofGenList = typeof (List<>);
object ConvertToList (ArrayList col, Type type) {
Type elementType = null;
if (type != null && type.HasElementType)
elementType = type.GetElementType ();
IList list;
if (type == null || type.IsArray || typeofObject == type || typeof (ArrayList).IsAssignableFrom (type))
list = new ArrayList ();
else if (ReflectionUtils.IsInstantiatableType (type))
// non-generic typed list
list = (IList) Activator.CreateInstance (type, true);
else if (ReflectionUtils.IsAssignable (type, typeofGenList)) {
if (type.IsGenericType) {
Type [] genArgs = type.GetGenericArguments ();
elementType = genArgs [0];
// generic list
list = (IList) Activator.CreateInstance (typeofGenList.MakeGenericType (genArgs));
} else
list = new ArrayList ();
} else
throw new InvalidOperationException (String.Format ("Deserializing list type '{0}' not supported.", type.GetType ().Name));
if (list.IsReadOnly) {
EvaluateList (col);
return list;
}
if (elementType == null)
elementType = typeof (object);
foreach (object value in col)
list.Add (ConvertToType (value, elementType));
if (type != null && type.IsArray)
list = ((ArrayList) list).ToArray (elementType);
return list;
}
object ConvertToObject (IDictionary<string, object> dict, Type type)
{
if (_typeResolver != null) {
if (dict.Keys.Contains(SerializedTypeNameKey)) {
// already Evaluated
type = _typeResolver.ResolveType ((string) dict [SerializedTypeNameKey]);
}
}
if (type.IsGenericType) {
if (type.GetGenericTypeDefinition ().IsAssignableFrom (typeof (IDictionary <,>))) {
Type[] arguments = type.GetGenericArguments ();
if (arguments == null || arguments.Length != 2 || (arguments [0] != typeof (object) && arguments [0] != typeof (string)))
throw new InvalidOperationException (
"Type '" + type + "' is not not supported for serialization/deserialization of a dictionary, keys must be strings or objects.");
if (type.IsAbstract) {
Type dictType = typeof (Dictionary <,>);
type = dictType.MakeGenericType (arguments [0], arguments [1]);
}
}
} else if (type.IsAssignableFrom (typeof (IDictionary)))
type = typeof (Dictionary <string, object>);
object target = Activator.CreateInstance (type, true);
foreach (KeyValuePair<string, object> entry in dict) {
object value = entry.Value;
if (target is IDictionary) {
Type valueType = ReflectionUtils.GetTypedDictionaryValueType (type);
if (value != null && valueType == typeof (System.Object))
valueType = value.GetType ();
((IDictionary) target).Add (entry.Key, ConvertToType (value, valueType));
continue;
}
MemberInfo [] memberCollection = type.GetMember (entry.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (memberCollection == null || memberCollection.Length == 0) {
//must evaluate value
Evaluate (value);
continue;
}
MemberInfo member = memberCollection [0];
if (!ReflectionUtils.CanSetMemberValue (member)) {
//must evaluate value
Evaluate (value);
continue;
}
Type memberType = ReflectionUtils.GetMemberUnderlyingType (member);
if (memberType.IsInterface) {
if (memberType.IsGenericType)
memberType = ResolveGenericInterfaceToType (memberType);
else
memberType = ResolveInterfaceToType (memberType);
if (memberType == null)
throw new InvalidOperationException ("Unable to deserialize a member, as its type is an unknown interface.");
}
ReflectionUtils.SetMemberValue (member, target, ConvertToType(value, memberType));
}
return target;
}
Type ResolveGenericInterfaceToType (Type type)
{
Type[] genericArgs = type.GetGenericArguments ();
if (ReflectionUtils.IsSubClass (type, typeof (IDictionary <,>)))
return typeof (Dictionary <,>).MakeGenericType (genericArgs);
if (ReflectionUtils.IsSubClass (type, typeof (IList <>)) ||
ReflectionUtils.IsSubClass (type, typeof (ICollection <>)) ||
ReflectionUtils.IsSubClass (type, typeof (IEnumerable <>))
)
return typeof (List <>).MakeGenericType (genericArgs);
if (ReflectionUtils.IsSubClass (type, typeof (IComparer <>)))
return typeof (Comparer <>).MakeGenericType (genericArgs);
if (ReflectionUtils.IsSubClass (type, typeof (IEqualityComparer <>)))
return typeof (EqualityComparer <>).MakeGenericType (genericArgs);
return null;
}
Type ResolveInterfaceToType (Type type)
{
if (typeof (IDictionary).IsAssignableFrom (type))
return typeof (Hashtable);
if (typeof (IList).IsAssignableFrom (type) ||
typeof (ICollection).IsAssignableFrom (type) ||
typeof (IEnumerable).IsAssignableFrom (type))
return typeof (ArrayList);
if (typeof (IComparer).IsAssignableFrom (type))
return typeof (Comparer);
return null;
}
public object DeserializeObject (string input) {
object obj = Evaluate (DeserializeObjectInternal (input), true);
IDictionary dictObj = obj as IDictionary;
if (dictObj != null && dictObj.Contains(SerializedTypeNameKey)){
if (_typeResolver == null) {
throw new ArgumentNullException ("resolver", "Must have a type resolver to deserialize an object that has an '__type' member");
}
obj = ConvertToType(obj, null);
}
return obj;
}
internal object DeserializeObjectInternal (string input) {
return Json.Deserialize (input, this);
}
internal object DeserializeObjectInternal (TextReader input) {
return Json.Deserialize (input, this);
}
public void RegisterConverters (IEnumerable<JavaScriptConverter> converters) {
if (converters == null)
throw new ArgumentNullException ("converters");
if (_converterList == null)
_converterList = new List<IEnumerable<JavaScriptConverter>> ();
_converterList.Add (converters);
}
internal JavaScriptConverter GetConverter (Type type) {
if (_converterList != null)
for (int i = 0; i < _converterList.Count; i++) {
foreach (JavaScriptConverter converter in _converterList [i])
foreach (Type supportedType in converter.SupportedTypes)
if (supportedType.IsAssignableFrom (type))
return converter;
}
return null;
}
public string Serialize (object obj) {
StringBuilder b = new StringBuilder ();
Serialize (obj, b);
return b.ToString ();
}
public void Serialize (object obj, StringBuilder output) {
Json.Serialize (obj, this, output);
}
internal void Serialize (object obj, TextWriter output) {
Json.Serialize (obj, this, output);
}
}
}

View File

@ -0,0 +1,43 @@
//
// JavaScriptTypeResolver.cs
//
// Author:
// Igor Zelmanovich <igorz@mainsoft.com>
//
// (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
//
//
// 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.
//
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Web.Script.Serialization
{
public abstract class JavaScriptTypeResolver
{
protected JavaScriptTypeResolver () { }
public abstract Type ResolveType (string id);
public abstract string ResolveTypeId (Type type);
}
}

View File

@ -0,0 +1,69 @@
//
// Json.cs
//
// Author:
// Marek Habersack <mhabersack@novell.com>
//
// (C) 2008 Novell, Inc. http://novell.com/
//
//
// 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.
//
using System;
using System.IO;
using System.Text;
namespace System.Web.Script.Serialization
{
internal static class Json
{
public static void Serialize (object obj, JavaScriptSerializer jss, StringBuilder output)
{
JsonSerializer js = new JsonSerializer (jss);
js.Serialize (obj, output);
js = null;
}
public static void Serialize (object obj, JavaScriptSerializer jss, TextWriter output)
{
JsonSerializer js = new JsonSerializer (jss);
js.Serialize (obj, output);
js = null;
}
public static object Deserialize (string input, JavaScriptSerializer jss)
{
if (jss == null)
throw new ArgumentNullException ("jss");
return Deserialize (new StringReader (input), jss);
}
public static object Deserialize (TextReader input, JavaScriptSerializer jss)
{
if (jss == null)
throw new ArgumentNullException ("jss");
JsonDeserializer ser = new JsonDeserializer (jss);
return ser.Deserialize (input);
}
}
}

View File

@ -0,0 +1,40 @@
//
// ScriptIgnoreAttribute.cs
//
// Author:
// Igor Zelmanovich <igorz@mainsoft.com>
//
// (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
//
//
// 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.
//
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Web.Script.Serialization
{
[AttributeUsage (AttributeTargets.Property | AttributeTargets.Field)]
public sealed class ScriptIgnoreAttribute : Attribute
{
}
}

View File

@ -0,0 +1,48 @@
//
// SimpleTypeResolver.cs
//
// Author:
// Igor Zelmanovich <igorz@mainsoft.com>
//
// (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
//
//
// 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.
//
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Web.Script.Serialization
{
public class SimpleTypeResolver : JavaScriptTypeResolver
{
public override Type ResolveType (string id)
{
return Type.GetType (id);
}
public override string ResolveTypeId (Type type)
{
return type.AssemblyQualifiedName;
}
}
}

View File

@ -0,0 +1,175 @@
//
// StringBuilderExtensions.cs
//
// Author:
// Marek Habersack <mhabersack@novell.com>
//
// (C) 2008 Novell, Inc. http://novell.com/
//
//
// 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.
//
using System;
using System.Text;
namespace System.Web.Script.Serialization
{
internal static class StringBuilderExtensions
{
static void CheckCount (StringBuilder sb, int maxCount)
{
if (sb.Length > maxCount)
throw new InvalidOperationException ("Maximum length exceeded.");
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, char[] value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, string value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, bool value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, byte value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, decimal value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, double value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, short value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, int value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, long value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, object value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, sbyte value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, float value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, ushort value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, uint value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, ulong value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, char value)
{
StringBuilder ret = sb.Append (value);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, char value, int repeatCount)
{
StringBuilder ret = sb.Append (value, repeatCount);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, char[] value, int startIndex, int charCount )
{
StringBuilder ret = sb.Append (value, startIndex, charCount);
CheckCount (sb, maxCount);
return ret;
}
public static StringBuilder AppendCount (StringBuilder sb, int maxCount, string value, int startIndex, int count)
{
StringBuilder ret = sb.Append (value, startIndex, count);
CheckCount (sb, maxCount);
return ret;
}
}
}