Пример #1
0
        public override Json Serialize(Type t, Object obj)
        {
            if (obj == null) return new Json(null);
            if (t.IsNullable()) return Json.Serialize(obj.UndecorateNullable(), t.UndecorateNullable());
            if (t == typeof(DateTime)) return new Json(obj.AssertCast<DateTime>().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffZ"));

            var cfg = t.Config().DefaultEngine().Config;
            if (cfg.IsPrimitive)
            {
                if (t.IsJsonPrimitive())
                {
                    return new JsonPrimitive(obj);
                }
                else
                {
                    t.SupportsSerializationToString().AssertTrue();
                    return new JsonPrimitive(obj.ToInvariantString());
                }
            }
            else
            {
                if (cfg.IsHash)
                {
                    var cast = typeof(EnumerableExtensions).GetMethod("Cast", BF.PublicStatic).AssertNotNull();
                    cast = cast.XMakeGenericMethod(typeof(String), typeof(Object));
                    var hash = (IDictionary<String, Object>)cast.Invoke(null, new[]{obj});

                    var json = new JsonObject();
                    hash.ForEach(kvp =>
                    {
                        var key = kvp.Key;
                        var value = Json.Serialize(kvp.Value);
                        json.Add(key, value);
                    });

                    return json;
                }
                else if (cfg.IsList)
                {
                    var list = ((IEnumerable)obj).Cast<Object>();

                    var json = new JsonArray();
                    list.ForEach(value =>
                    {
                        var j_value = Json.Serialize(value);
                        json.Add(j_value);
                    });

                    return json;
                }
                else if (cfg.IsObject)
                {
                    var json = new JsonObject();

                    cfg.Slots.Where(mi => mi.CanRead()).ForEach(mi =>
                    {
                        var a_include = mi.AttrOrNull<JsonIncludeAttribute>();
                        var a_key = a_include == null ? null : a_include.Name;
                        var key = a_key ?? (cfg.LowercaseSlotNames ? mi.Name.ToLower() : mi.Name);
                        var value = mi.GetValue(obj);
                        var j_value = Json.Serialize(value, mi);
                        json.Add(key, j_value);
                    });

                    return json;
                }
                else
                {
                    throw AssertionHelper.Fail();
                }
            }
        }