Exemple #1
0
        public void Serialize(object obj, SerializationOptions options)
        {
            if (obj == null)
            {
                Write("null");
                return;
            }

            var objectType = obj.GetType();

            var converter = options?.Converters?.FirstOrDefault(c => c.GetConvertingType() == objectType);

            if (converter != null)
            {
                Serialize(converter.Serializer(obj), options);
                return;
            }

            Func <object, string> cnv;
            Type genericType;

            if (!SerializerCache.TryGetValue(objectType, out cnv))
            {
                var strConverter = new Func <object, string>(
                    s =>
                {
                    var t = (string)s;
                    var r = "\"";

                    for (var i = 0; i < t.Length; i++)
                    {
                        var c = t[i];

                        r += c == '\r' ? "\\r" :
                             c == '\n' ? "\\n" :
                             c == '\t' ? "\\t" :
                             c == '"' ? "\\\"" :
                             c == '\\' ? "\\\\" :
                             c == '/' ? "\\/" :
                             c == '\b' ? "\\b" :
                             c == '\f' ? "\\f" :
                             c.ToString();
                    }

                    r += "\"";

                    return(r);
                });

                if (obj is string)
                {
                    cnv = strConverter;
                }
                else if (obj is IEnumerable)
                {
                    Write(obj is IDictionary ? "{" : "[");

                    var first = true;

                    foreach (var o in (IEnumerable)obj)
                    {
                        if (first)
                        {
                            first = false;
                        }
                        else
                        {
                            Write(",");
                        }

                        Serialize(o, options);
                    }

                    Write(obj is IDictionary ? "}" : "]");
                    return;
                }
                else if (obj is bool || obj is bool?)
                {
                    cnv = b => (bool)b ? "true" : "false";
                }
                else if (obj is int || obj is int? ||
                         obj is short || obj is short? ||
                         obj is long || obj is long? ||
                         obj is uint || obj is uint? ||
                         obj is ushort || obj is ushort? ||
                         obj is ulong || obj is ulong? ||
                         obj is float || obj is float? ||
                         obj is double || obj is double? ||
                         obj is decimal || obj is decimal?||
                         obj is float || obj is uint? ||
                         obj is ushort || obj is ushort? ||
                         obj is ulong || obj is ulong?)
                {
                    cnv = n => string.Format(CultureInfo.InvariantCulture, "{0}", n);
                }
                else if (obj is DateTime || obj is DateTime?)
                {
                    cnv = d => strConverter(((DateTime)d).ToString(CultureInfo.InvariantCulture));
                }
                else if (obj is DateTimeOffset || obj is DateTimeOffset?)
                {
                    cnv = d => strConverter(((DateTimeOffset)d).ToString(CultureInfo.InvariantCulture));
                }
                else if (obj is TimeSpan || obj is TimeSpan?)
                {
                    cnv = d => strConverter(((TimeSpan)d).ToString("c"));
                }
                else if (obj is Enum)
                {
                    cnv = e => ((int)e).ToString(CultureInfo.InvariantCulture);
                }
                else if (objectType.IsGenericType &&
                         objectType.GenericTypeArguments.Length == 2 &&
                         objectType == (genericType = typeof(KeyValuePair <,>).MakeGenericType(objectType.GenericTypeArguments)))
                {
                    var k = genericType.GetProperty("Key").GetValue(obj).ToString();
                    var v = genericType.GetProperty("Value").GetValue(obj);

                    Write(strConverter(k));
                    Write(":");
                    Serialize(v, options);
                    return;
                }
                else if (!objectType.IsPrimitive)
                {
                    Write("{");

                    var first = true;

                    foreach (var m in SerializerMap.GetSerializerMap(objectType)
                             .Members)
                    {
                        if (first)
                        {
                            first = false;
                        }
                        else
                        {
                            Write(",");
                        }

                        if (objectType == typeof(DictionaryEntry))
                        {
                            var d = (DictionaryEntry)obj;
                            Write(strConverter(d.Key.ToString()));
                            Write(":");
                            Serialize(d.Value, options);
                        }
                        else
                        {
                            string memberName = m.Name;
                            if (options?.PropertyNameTransform != null)
                            {
                                memberName = options?.PropertyNameTransform.Transform(m.Name);
                            }
                            Write(strConverter(memberName));
                            Write(":");

                            try
                            {
                                Serialize(m.GetValue(obj), options);
                            }
                            catch (TargetInvocationException)
                            {
                                Serialize(null, options);
                            }
                        }
                    }

                    Write("}");
                    return;
                }

                SerializerCache[objectType] =
                    cnv ??
                    throw new InvalidOperationException(
                              "Unknown object type! " + objectType.FullName);;
            }

            Write(cnv(obj));
        }
Exemple #2
0
 /// <summary>
 /// Deserializes an object from a JSON text stream.
 /// </summary>
 /// <typeparam name="T">Deserialized object's type</typeparam>
 /// <param name="stream">Source JSON text stream</param>
 /// <param name="options">Serialization options.</param>
 /// <returns></returns>
 public static T Deserialize <T>(Stream stream, SerializationOptions options = null)
 {
     return((T)JsonParser.Instance.Initialize(new StreamReader(stream), options)
            .FromJson(typeof(T)));
 }
Exemple #3
0
 /// <summary>
 /// Deserializes an object from a JSON text reader.
 /// </summary>
 /// <typeparam name="T">Deserialized object's type</typeparam>
 /// <param name="reader">Source JSON text reader</param>
 /// <param name="options">Serialization options.</param>
 /// <returns></returns>
 public static T Deserialize <T>(TextReader reader, SerializationOptions options = null)
 {
     return((T)JsonParser.Instance.Initialize(reader, options)
            .FromJson(typeof(T)));
 }
Exemple #4
0
 /// <summary>
 /// Deserializes an object from a JSON text.
 /// </summary>
 /// <typeparam name="T">Deserialized object's type</typeparam>
 /// <param name="json">JSON text</param>
 /// <param name="options">Serialization options.</param>
 /// <returns></returns>
 public static T Deserialize <T>(string json, SerializationOptions options = null)
 {
     return((T)JsonParser.Instance.Initialize(json, options)
            .FromJson(typeof(T)));
 }