1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
|
//
// JsonSerializer.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.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
namespace System.Web.Script.Serialization
{
internal sealed class JsonSerializer
{
internal static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
static readonly DateTime MinimumJavaScriptDate = new DateTime (100, 1, 1, 0, 0, 0, DateTimeKind.Utc);
static readonly MethodInfo serializeGenericDictionary = typeof (JsonSerializer).GetMethod ("SerializeGenericDictionary", BindingFlags.NonPublic | BindingFlags.Instance);
Dictionary <object, bool> objectCache;
JavaScriptSerializer serializer;
JavaScriptTypeResolver typeResolver;
int recursionLimit;
int maxJsonLength;
int recursionDepth;
Dictionary <Type, MethodInfo> serializeGenericDictionaryMethods;
public JsonSerializer (JavaScriptSerializer serializer)
{
if (serializer == null)
throw new ArgumentNullException ("serializer");
this.serializer = serializer;
typeResolver = serializer.TypeResolver;
recursionLimit = serializer.RecursionLimit;
maxJsonLength = serializer.MaxJsonLength;
}
public void Serialize (object obj, StringBuilder output)
{
if (output == null)
throw new ArgumentNullException ("output");
DoSerialize (obj, output);
}
public void Serialize (object obj, TextWriter output)
{
if (output == null)
throw new ArgumentNullException ("output");
StringBuilder sb = new StringBuilder ();
DoSerialize (obj, sb);
output.Write (sb.ToString ());
}
void DoSerialize (object obj, StringBuilder output)
{
recursionDepth = 0;
objectCache = new Dictionary <object, bool> ();
SerializeValue (obj, output);
}
void SerializeValue (object obj, StringBuilder output)
{
recursionDepth++;
SerializeValueImpl (obj, output);
recursionDepth--;
}
void SerializeValueImpl (object obj, StringBuilder output)
{
if (recursionDepth > recursionLimit)
throw new ArgumentException ("Recursion limit has been exceeded while serializing object of type '{0}'", obj != null ? obj.GetType ().ToString () : "[null]");
if (obj == null || DBNull.Value.Equals (obj)) {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "null");
return;
}
Type valueType = obj.GetType ();
JavaScriptConverter jsc = serializer.GetConverter (valueType);
if (jsc != null) {
IDictionary <string, object> result = jsc.Serialize (obj, serializer);
if (result == null) {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "null");
return;
}
if (typeResolver != null) {
string typeId = typeResolver.ResolveTypeId (valueType);
if (!String.IsNullOrEmpty (typeId))
result [JavaScriptSerializer.SerializedTypeNameKey] = typeId;
}
SerializeValue (result, output);
return;
}
TypeCode typeCode = Type.GetTypeCode (valueType);
switch (typeCode) {
case TypeCode.String:
WriteValue (output, (string)obj);
return;
case TypeCode.Char:
WriteValue (output, (char)obj);
return;
case TypeCode.Boolean:
WriteValue (output, (bool)obj);
return;
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.Byte:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
if (valueType.IsEnum) {
WriteEnumValue (output, obj, typeCode);
return;
}
goto case TypeCode.Decimal;
case TypeCode.Single:
WriteValue (output, (float)obj);
return;
case TypeCode.Double:
WriteValue (output, (double)obj);
return;
case TypeCode.Decimal:
WriteValue (output, obj as IConvertible);
return;
case TypeCode.DateTime:
WriteValue (output, (DateTime)obj);
return;
}
if (typeof (Uri).IsAssignableFrom (valueType)) {
WriteValue (output, (Uri)obj);
return;
}
if (typeof (Guid).IsAssignableFrom (valueType)) {
WriteValue (output, (Guid)obj);
return;
}
IConvertible convertible = obj as IConvertible;
if (convertible != null) {
WriteValue (output, convertible);
return;
}
try {
if (objectCache.ContainsKey (obj))
throw new InvalidOperationException ("Circular reference detected.");
objectCache.Add (obj, true);
Type closedIDict = GetClosedIDictionaryBase(valueType);
if (closedIDict != null) {
if (serializeGenericDictionaryMethods == null)
serializeGenericDictionaryMethods = new Dictionary <Type, MethodInfo> ();
MethodInfo mi;
if (!serializeGenericDictionaryMethods.TryGetValue (closedIDict, out mi)) {
Type[] types = closedIDict.GetGenericArguments ();
mi = serializeGenericDictionary.MakeGenericMethod (types [0], types [1]);
serializeGenericDictionaryMethods.Add (closedIDict, mi);
}
mi.Invoke (this, new object[] {output, obj});
return;
}
IDictionary dict = obj as IDictionary;
if (dict != null) {
SerializeDictionary (output, dict);
return;
}
IEnumerable enumerable = obj as IEnumerable;
if (enumerable != null) {
SerializeEnumerable (output, enumerable);
return;
}
SerializeArbitraryObject (output, obj, valueType);
} finally {
objectCache.Remove (obj);
}
}
Type GetClosedIDictionaryBase(Type t) {
if(t.IsGenericType && typeof (IDictionary <,>).IsAssignableFrom (t.GetGenericTypeDefinition ()))
return t;
foreach(Type iface in t.GetInterfaces()) {
if(iface.IsGenericType && typeof (IDictionary <,>).IsAssignableFrom (iface.GetGenericTypeDefinition ()))
return iface;
}
return null;
}
bool ShouldIgnoreMember (MemberInfo mi, out MethodInfo getMethod)
{
getMethod = null;
if (mi == null)
return true;
if (mi.IsDefined (typeof (ScriptIgnoreAttribute), true))
return true;
FieldInfo fi = mi as FieldInfo;
if (fi != null)
return false;
PropertyInfo pi = mi as PropertyInfo;
if (pi == null)
return true;
getMethod = pi.GetGetMethod ();
if (getMethod == null || getMethod.GetParameters ().Length > 0) {
getMethod = null;
return true;
}
return false;
}
object GetMemberValue (object obj, MemberInfo mi)
{
FieldInfo fi = mi as FieldInfo;
if (fi != null)
return fi.GetValue (obj);
MethodInfo method = mi as MethodInfo;
if (method == null)
throw new InvalidOperationException ("Member is not a method (internal error).");
object ret;
try {
ret = method.Invoke (obj, null);
} catch (TargetInvocationException niex) {
if (niex.InnerException is NotImplementedException) {
Console.WriteLine ("!!! COMPATIBILITY WARNING. FEATURE NOT IMPLEMENTED. !!!");
Console.WriteLine (niex);
Console.WriteLine ("!!! RETURNING NULL. PLEASE LET MONO DEVELOPERS KNOW ABOUT THIS EXCEPTION. !!!");
return null;
}
throw;
}
return ret;
}
void SerializeArbitraryObject (StringBuilder output, object obj, Type type)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
bool first = true;
if (typeResolver != null) {
string typeId = typeResolver.ResolveTypeId (type);
if (!String.IsNullOrEmpty (typeId)) {
WriteDictionaryEntry (output, first, JavaScriptSerializer.SerializedTypeNameKey, typeId);
first = false;
}
}
SerializeMembers <FieldInfo> (type.GetFields (BindingFlags.Public | BindingFlags.Instance), obj, output, ref first);
SerializeMembers <PropertyInfo> (type.GetProperties (BindingFlags.Public | BindingFlags.Instance), obj, output, ref first);
StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
}
void SerializeMembers <T> (T[] members, object obj, StringBuilder output, ref bool first) where T: MemberInfo
{
MemberInfo member;
MethodInfo getMethod;
string name;
foreach (T mi in members) {
if (ShouldIgnoreMember (mi as MemberInfo, out getMethod))
continue;
name = mi.Name;
if (getMethod != null)
member = getMethod;
else
member = mi;
WriteDictionaryEntry (output, first, name, GetMemberValue (obj, member));
if (first)
first = false;
}
}
void SerializeEnumerable (StringBuilder output, IEnumerable enumerable)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "[");
bool first = true;
foreach (object value in enumerable) {
if (!first)
StringBuilderExtensions.AppendCount (output, maxJsonLength, ',');
SerializeValue (value, output);
if (first)
first = false;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "]");
}
void SerializeDictionary (StringBuilder output, IDictionary dict)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
bool first = true;
foreach (DictionaryEntry entry in dict) {
WriteDictionaryEntry (output, first, entry.Key as string, entry.Value);
if (first)
first = false;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
}
void SerializeGenericDictionary <TKey, TValue> (StringBuilder output, IDictionary <TKey, TValue> dict)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, "{");
bool first = true;
foreach (KeyValuePair <TKey, TValue> kvp in dict) {
WriteDictionaryEntry (output, first, kvp.Key as string, kvp.Value);
if (first)
first = false;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "}");
}
void WriteDictionaryEntry (StringBuilder output, bool skipComma, string key, object value)
{
if (key == null)
throw new InvalidOperationException ("Only dictionaries with keys convertible to string are supported.");
if (!skipComma)
StringBuilderExtensions.AppendCount (output, maxJsonLength, ',');
WriteValue (output, key);
StringBuilderExtensions.AppendCount (output, maxJsonLength, ':');
SerializeValue (value, output);
}
void WriteEnumValue (StringBuilder output, object value, TypeCode typeCode)
{
switch (typeCode) {
case TypeCode.SByte:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (sbyte)value);
return;
case TypeCode.Int16:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (short)value);
return;
case TypeCode.UInt16:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (ushort)value);
return;
case TypeCode.Int32:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (int)value);
return;
case TypeCode.Byte:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (byte)value);
return;
case TypeCode.UInt32:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (uint)value);
return;
case TypeCode.Int64:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (long)value);
return;
case TypeCode.UInt64:
StringBuilderExtensions.AppendCount (output, maxJsonLength, (ulong)value);
return;
default:
throw new InvalidOperationException (String.Format ("Invalid type code for enum: {0}", typeCode));
}
}
void WriteValue (StringBuilder output, float value)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, value.ToString ("r", CultureInfo.InvariantCulture));
}
void WriteValue (StringBuilder output, double value)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, value.ToString ("r", CultureInfo.InvariantCulture));
}
void WriteValue (StringBuilder output, Guid value)
{
WriteValue (output, value.ToString ());
}
void WriteValue (StringBuilder output, Uri value)
{
WriteValue (output, value.OriginalString);
}
void WriteValue (StringBuilder output, DateTime value)
{
value = value.ToUniversalTime ();
if (value < MinimumJavaScriptDate)
value = MinimumJavaScriptDate;
long ticks = (value.Ticks - InitialJavaScriptDateTicks) / (long)10000;
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"\\/Date(" + ticks + ")\\/\"");
}
void WriteValue (StringBuilder output, IConvertible value)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, value.ToString (CultureInfo.InvariantCulture));
}
void WriteValue (StringBuilder output, bool value)
{
StringBuilderExtensions.AppendCount (output, maxJsonLength, value ? "true" : "false");
}
void WriteValue (StringBuilder output, char value)
{
if (value == '\0') {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "null");
return;
}
WriteValue (output, value.ToString ());
}
void WriteValue (StringBuilder output, string value)
{
if (String.IsNullOrEmpty (value)) {
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"\"");
return;
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"");
char c;
for (int i = 0; i < value.Length; i++) {
c = value [i];
switch (c) {
case '\t':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\t");
break;
case '\n':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\n");
break;
case '\r':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\r");
break;
case '\f':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\f");
break;
case '\b':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\b");
break;
case '<':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u003c");
break;
case '>':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u003e");
break;
case '"':
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\\\"");
break;
case '\'':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u0027");
break;
case '\\':
StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\\");
break;
default:
if (c > '\u001f')
StringBuilderExtensions.AppendCount (output, maxJsonLength, c);
else {
output.Append("\\u00");
int intVal = (int) c;
StringBuilderExtensions.AppendCount (output, maxJsonLength, (char) ('0' + (intVal >> 4)));
intVal &= 0xf;
StringBuilderExtensions.AppendCount (output, maxJsonLength, (char) (intVal < 10 ? '0' + intVal : 'a' + (intVal - 10)));
}
break;
}
}
StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"");
}
}
}
|