예제 #1
0
        public static string ToJSON(object target)
        {
            if (target == null)
            {
                return("null");
            }
            var type       = target.GetType();
            var _attribute = type.GetCustomAttributes(false).OfType <JSONClassAttribute>().FirstOrDefault(x => !string.IsNullOrEmpty(x.Advocate));

            if (_attribute != null)
            {
                var _property = type.GetProperty(_attribute.Advocate);
                if (_property == null)
                {
                    throw new Exception("The Advocate (" + _attribute.Advocate + ") doesn't exist on class (" + type.Name + ")");
                }
                return(ToJSON(_property.GetValue(target)));
            }
            var _typecode = Type.GetTypeCode(type);
            var isQuoted  = type.IsEnum || _typecode == TypeCode.String;
            var _string   = "";

            if (_typecode == TypeCode.Object)
            {
                if (target is DynamicObject dio)
                {
                    var dict = dio.GetDynamicMemberNames().ToDictionary(x => x, y => dio.TryGetMember(new DynamicAccess(y, true), out var result) ? result : null);
                    return(ToJSON(dict));
                }
                else if (target is IDictionary dict)
                {
                    var KeyPairs = (Keys : new object[dict.Count], Values : new object[dict.Count]);
                    dict.Keys.CopyTo(KeyPairs.Keys, 0);
                    dict.Values.CopyTo(KeyPairs.Values, 0);
                    return("{" + string.Join(",", KeyPairs.Keys.Zip(KeyPairs.Values, (k, v) => "\"" + k.ToString() + "\":" + ToJSON(v)).ToArray()) + "}");
                }
                else if (type.IsArray || type.GetInterface("ICollection") != null || type.GetInterface("IEnumerable") != null)
                {
                    var _l = new JSONBuilder();
                    foreach (var item in (ICollection)target)
                    {
                        _l.Add(ToJSON(item));
                    }
                    _string += "[" + string.Join(",", _l) + "]";
                }
                else
                {
                    return("{" + string.Join(",", GetAttributeDefinitions(type).Where(x => !x.IgnoreTo).Select(x =>
                    {
                        var Value = x.CustomConvertTo ? ((IJSONValueConverter)target).ConvertToJSON(x.Name, x.property.GetValue(target), x.property) : ToJSON(x.property.GetValue(target));
                        return "\"" + x.Name + "\":" + Value;
                    })) + "}");
                }
            }
            else
            {
                return((isQuoted ? "\"" : "") + (_typecode == TypeCode.Boolean ? target.ToString().ToLower() : target.ToString()) + (isQuoted ? "\"" : ""));
            }
            return(_string);
        }