public static string GetJsonName(object value)
    {
        if (value == null)
        {
            return(null);
        }
        Type       type       = value.GetType();
        MemberInfo memberInfo = null;

        if (type.IsEnum)
        {
            string name = Enum.GetName(type, value);
            if (string.IsNullOrEmpty(name))
            {
                return(null);
            }
            memberInfo = type.GetField(name);
        }
        else
        {
            memberInfo = (value as MemberInfo);
        }
        if (memberInfo == null)
        {
            throw new ArgumentException();
        }
        if (!Attribute.IsDefined(memberInfo, typeof(JsonNameAttribute)))
        {
            return(null);
        }
        JsonNameAttribute jsonNameAttribute = (JsonNameAttribute)Attribute.GetCustomAttribute(memberInfo, typeof(JsonNameAttribute));

        return(jsonNameAttribute.Name);
    }
            public virtual void Write(Enum value)
            {
                string enumName = null;

                Type type = value.GetType();

                if (type.IsDefined(typeof(FlagsAttribute), true) && !Enum.IsDefined(type, value))
                {
                    Enum[]   flags     = JsonWriter.GetFlagList(type, value);
                    string[] flagNames = new string[flags.Length];
                    for (int i = 0; i < flags.Length; i++)
                    {
                        flagNames[i] = JsonNameAttribute.GetJsonName(flags[i]);
                        if (String.IsNullOrEmpty(flagNames[i]))
                        {
                            flagNames[i] = flags[i].ToString("f");
                        }
                    }
                    enumName = String.Join(", ", flagNames);
                }
                else
                {
                    enumName = JsonNameAttribute.GetJsonName(value);
                    if (String.IsNullOrEmpty(enumName))
                    {
                        enumName = value.ToString("f");
                    }
                }

                this.Write(enumName);
            }
        /// <summary>
        /// Ctor.
        /// </summary>
        internal JsonServiceDescription(Type serviceType, string serviceUrl)
        {
            //TODO: clean up JsonServiceDescription efficiency

            if (serviceType == null)
            {
                return;
            }

            if (!JsonServiceAttribute.IsJsonService(serviceType))
            {
                throw new InvalidRequestException("Specified type is not marked as a JsonService.");
            }

            this.Namespace = JsonServiceAttribute.GetNamespace(serviceType);
            if (String.IsNullOrEmpty(this.Namespace))
            {
                this.name = serviceType.Namespace;
            }

            this.Name = JsonNameAttribute.GetJsonName(serviceType);
            if (String.IsNullOrEmpty(this.Name))
            {
                this.name = serviceType.Name;
            }

            MethodInfo[] infos = serviceType.GetMethods();
            List <JsonMethodDescription> methods = new List <JsonMethodDescription>(infos.Length);

            foreach (MethodInfo info in infos)
            {
                if (info.IsPublic && JsonMethodAttribute.IsJsonMethod(info))
                {
                    methods.Add(new JsonMethodDescription(info));
                }
            }
            this.Methods = methods.ToArray();

            this.ID = "urn:uuid:" + serviceType.GUID;

            Version assemblyVersion = serviceType.Assembly.GetName().Version;

            this.Version = assemblyVersion.ToString(2);

            this.Address = serviceUrl;

            this.Help = JsonServiceAttribute.GetHelpUrl(serviceType);

            if (Attribute.IsDefined(serviceType, typeof(DescriptionAttribute)))
            {
                DescriptionAttribute description = Attribute.GetCustomAttribute(serviceType, typeof(DescriptionAttribute), true) as DescriptionAttribute;
                this.Summary = description.Description;
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Gets the serialized name for the member.
        /// </summary>
        /// <param name="member"></param>
        /// <returns></returns>
        public override IEnumerable <DataName> GetName(MemberInfo member)
        {
            JsonNameAttribute attr = TypeCoercionUtility.GetAttribute <JsonNameAttribute>(member);

            // NOTE: JSON allows String.Empty as a valid property name
            if ((attr == null) || (attr.Name == null))
            {
                yield break;
            }

            yield return(new DataName(attr.Name));
        }
            protected virtual void WriteObject(object value, Type type)
            {
                bool appendDelim = false;

                this.Writer.Write(JsonReader.OperatorObjectStart);

                this.depth++;
                if (this.depth > this.settings.MaxDepth)
                {
                    throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
                }
                try
                {
                    if (!String.IsNullOrEmpty(this.settings.TypeHintName))
                    {
                        if (appendDelim)
                        {
                            this.WriteObjectPropertyDelim();
                        }
                        else
                        {
                            appendDelim = true;
                        }

                        this.WriteObjectProperty(this.settings.TypeHintName, type.FullName + ", " + type.Assembly.GetName().Name);
                    }

                    bool anonymousType = type.IsGenericType && type.Name.StartsWith(JsonWriter.AnonymousTypePrefix);

                    // serialize public properties
                    PropertyInfo[] properties = type.GetProperties();
                    foreach (PropertyInfo property in properties)
                    {
                        if (!property.CanRead)
                        {
                            continue;
                        }

                        if (!property.CanWrite && !anonymousType)
                        {
                            continue;
                        }

                        if (this.IsIgnored(type, property, value))
                        {
                            continue;
                        }

                        object propertyValue = property.GetValue(value, null);
                        if (this.IsDefaultValue(property, propertyValue))
                        {
                            continue;
                        }

                        if (appendDelim)
                        {
                            this.WriteObjectPropertyDelim();
                        }
                        else
                        {
                            appendDelim = true;
                        }

                        // use Attributes here to control naming
                        string propertyName = JsonNameAttribute.GetJsonName(property);
                        if (String.IsNullOrEmpty(propertyName))
                        {
                            propertyName = property.Name;
                        }

                        this.WriteObjectProperty(propertyName, propertyValue);
                    }

                    // serialize public fields
                    FieldInfo[] fields = type.GetFields();
                    foreach (FieldInfo field in fields)
                    {
                        if (!field.IsPublic || field.IsStatic)
                        {
                            continue;
                        }

                        if (this.IsIgnored(type, field, value))
                        {
                            continue;
                        }

                        object fieldValue = field.GetValue(value);
                        if (this.IsDefaultValue(field, fieldValue))
                        {
                            continue;
                        }

                        if (appendDelim)
                        {
                            this.WriteObjectPropertyDelim();
                            this.WriteLine();
                        }
                        else
                        {
                            appendDelim = true;
                        }

                        // use Attributes here to control naming
                        string fieldName = JsonNameAttribute.GetJsonName(field);
                        if (String.IsNullOrEmpty(fieldName))
                        {
                            fieldName = field.Name;
                        }

                        this.WriteObjectProperty(fieldName, fieldValue);
                    }
                }
                finally
                {
                    this.depth--;
                }

                if (appendDelim)
                {
                    this.WriteLine();
                }
                this.Writer.Write(JsonReader.OperatorObjectEnd);
            }
            internal object CoerceType(Type targetType, object value)
            {
                bool isNullable = TypeCoercionUtility.IsNullable(targetType);

                if (value == null)
                {
                    if (!allowNullValueTypes &&
                        targetType.IsValueType &&
                        !isNullable)
                    {
                        throw new JsonTypeCoercionException(String.Format(TypeCoercionUtility.ErrorNullValueType, targetType.FullName));
                    }
                    return(value);
                }

                if (isNullable)
                {
                    // nullable types have a real underlying struct
                    Type[] genericArgs = targetType.GetGenericArguments();
                    if (genericArgs.Length == 1)
                    {
                        targetType = genericArgs[0];
                    }
                }

                Type actualType = value.GetType();

                if (targetType.IsAssignableFrom(actualType))
                {
                    return(value);
                }

                if (targetType.IsEnum)
                {
                    if (value is String)
                    {
                        if (!Enum.IsDefined(targetType, value))
                        {
                            // if isn't a defined value perhaps it is the JsonName
                            foreach (FieldInfo field in targetType.GetFields())
                            {
                                string jsonName = JsonNameAttribute.GetJsonName(field);
                                if (((string)value).Equals(jsonName))
                                {
                                    value = field.Name;
                                    break;
                                }
                            }
                        }

                        return(Enum.Parse(targetType, (string)value));
                    }
                    else
                    {
                        value = this.CoerceType(Enum.GetUnderlyingType(targetType), value);
                        return(Enum.ToObject(targetType, value));
                    }
                }

                if (value is IDictionary)
                {
                    Dictionary <string, MemberInfo> memberMap;
                    return(this.CoerceType(targetType, (IDictionary)value, out memberMap));
                }

                if (typeof(IEnumerable).IsAssignableFrom(targetType) &&
                    typeof(IEnumerable).IsAssignableFrom(actualType))
                {
                    return(this.CoerceList(targetType, actualType, (IEnumerable)value));
                }

                if (value is String)
                {
                    if (targetType == typeof(DateTime))
                    {
                        DateTime date;
                        if (DateTime.TryParse(
                                (string)value,
                                DateTimeFormatInfo.InvariantInfo,
                                DateTimeStyles.RoundtripKind | DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.NoCurrentDateDefault,
                                out date))
                        {
                            return(date);
                        }
                    }
                    else if (targetType == typeof(Guid))
                    {
                        // try-catch is pointless since will throw upon generic conversion
                        return(new Guid((string)value));
                    }
                    else if (targetType == typeof(Char))
                    {
                        if (((string)value).Length == 1)
                        {
                            return(((string)value)[0]);
                        }
                    }
                    else if (targetType == typeof(Uri))
                    {
                        Uri uri;
                        if (Uri.TryCreate((string)value, UriKind.RelativeOrAbsolute, out uri))
                        {
                            return(uri);
                        }
                    }
                    else if (targetType == typeof(Version))
                    {
                        // try-catch is pointless since will throw upon generic conversion
                        return(new Version((string)value));
                    }
                }
                else if (targetType == typeof(TimeSpan))
                {
                    return(new TimeSpan((long)this.CoerceType(typeof(Int64), value)));
                }

                TypeConverter converter = TypeDescriptor.GetConverter(targetType);

                if (converter.CanConvertFrom(actualType))
                {
                    return(converter.ConvertFrom(value));
                }

                converter = TypeDescriptor.GetConverter(actualType);
                if (converter.CanConvertTo(targetType))
                {
                    return(converter.ConvertTo(value, targetType));
                }

                try
                {
                    // fall back to basics
                    return(Convert.ChangeType(value, targetType));
                }
                catch (Exception ex)
                {
                    throw new JsonTypeCoercionException(
                              String.Format("Error converting {0} to {1}", value.GetType().FullName, targetType.FullName), ex);
                }
            }
            private Dictionary <string, MemberInfo> CreateMemberMap(Type objectType)
            {
                if (this.MemberMapCache.ContainsKey(objectType))
                {
                    // map was stored in cache
                    return(this.MemberMapCache[objectType]);
                }

                // create a new map
                Dictionary <string, MemberInfo> memberMap = new Dictionary <string, MemberInfo>();

                // load properties into property map
                PropertyInfo[] properties = objectType.GetProperties();
                foreach (PropertyInfo info in properties)
                {
                    if (!info.CanRead || !info.CanWrite)
                    {
                        continue;
                    }

                    if (JsonIgnoreAttribute.IsJsonIgnore(info))
                    {
                        continue;
                    }

                    string jsonName = JsonNameAttribute.GetJsonName(info);
                    if (String.IsNullOrEmpty(jsonName))
                    {
                        memberMap[info.Name] = info;
                    }
                    else
                    {
                        memberMap[jsonName] = info;
                    }
                }

                // load public fields into property map
                FieldInfo[] fields = objectType.GetFields();
                foreach (FieldInfo info in fields)
                {
                    if (!info.IsPublic)
                    {
                        continue;
                    }

                    if (JsonIgnoreAttribute.IsJsonIgnore(info))
                    {
                        continue;
                    }

                    string jsonName = JsonNameAttribute.GetJsonName(info);
                    if (String.IsNullOrEmpty(jsonName))
                    {
                        memberMap[info.Name] = info;
                    }
                    else
                    {
                        memberMap[jsonName] = info;
                    }
                }

                // store in cache for repeated usage
                this.MemberMapCache[objectType] = memberMap;

                return(memberMap);
            }
Esempio n. 8
0
        // Token: 0x0600020D RID: 525 RVA: 0x00013798 File Offset: 0x00011998
        protected override void WriteObject(object value, Type type)
        {
            bool writeDelim = false;

            base.TextWriter.Write('{');
            this.WriteTab();
            this.depth++;
            try
            {
                if (!string.IsNullOrEmpty(base.Settings.TypeHintName))
                {
                    this.WriteObjectProperty(base.Settings.TypeHintName, type.FullName + ", " + type.Assembly.GetName().Name, delegate
                    {
                        if (writeDelim)
                        {
                            this.WriteObjectPropertyDelim();
                            return;
                        }
                        writeDelim = true;
                    });
                }
                bool flag = type.IsGenericType && type.Name.StartsWith("<>f__AnonymousType", StringComparison.Ordinal);
                foreach (PropertyInfo propertyInfo in type.GetProperties())
                {
                    if (propertyInfo.CanRead && (propertyInfo.CanWrite || flag) && !this.IsIgnored(type, propertyInfo, value))
                    {
                        object value2 = propertyInfo.GetValue(value, null);
                        if (!this.IsDefaultValue(propertyInfo, value2))
                        {
                            string text = JsonNameAttribute.GetJsonName(propertyInfo);
                            if (string.IsNullOrEmpty(text))
                            {
                                text = propertyInfo.Name;
                            }
                            this.WriteObjectProperty(text, value2, delegate
                            {
                                if (writeDelim)
                                {
                                    this.WriteObjectPropertyDelim();
                                    return;
                                }
                                writeDelim = true;
                            });
                        }
                    }
                }
                foreach (FieldInfo fieldInfo in type.GetFields())
                {
                    if (fieldInfo.IsPublic && !fieldInfo.IsStatic && !this.IsIgnored(type, fieldInfo, value))
                    {
                        object value3 = fieldInfo.GetValue(value);
                        if (!this.IsDefaultValue(fieldInfo, value3))
                        {
                            string text2 = JsonNameAttribute.GetJsonName(fieldInfo);
                            if (string.IsNullOrEmpty(text2))
                            {
                                text2 = fieldInfo.Name;
                            }
                            this.WriteObjectProperty(text2, value3, delegate
                            {
                                if (writeDelim)
                                {
                                    this.WriteObjectPropertyDelim();
                                    this.WriteLine();
                                    return;
                                }
                                writeDelim = true;
                            });
                        }
                    }
                }
            }
            finally
            {
                this.depth--;
            }
            if (writeDelim)
            {
                this.WriteLine();
            }
            base.TextWriter.Write('}');
        }
        protected override void WriteObject(object value, Type type)
        {
            bool writeDelim = false;

            TextWriter.Write('{');
            WriteTab();
            depth++;
            try {
                if (!string.IsNullOrEmpty(Settings.TypeHintName))
                {
                    this.WriteObjectProperty(Settings.TypeHintName, type.FullName + ", " + type.Assembly.GetName().Name,
                                             () => {
                        if (writeDelim)
                        {
                            this.WriteObjectPropertyDelim();
                        }
                        else
                        {
                            writeDelim = true;
                        }
                    });
                }
                bool isAnonymous = type.IsGenericType && type.Name.StartsWith("<>f__AnonymousType", StringComparison.Ordinal);
                foreach (var propertyInfo in type.GetProperties())
                {
                    if (propertyInfo.CanRead)
                    {
                        if (propertyInfo.CanWrite || isAnonymous)
                        {
                            if (!this.IsIgnored(type, propertyInfo, value))
                            {
                                object val = propertyInfo.GetValue(value, null);
                                if (!this.IsDefaultValue(propertyInfo, val))
                                {
                                    string key = JsonNameAttribute.GetJsonName(propertyInfo);
                                    if (string.IsNullOrEmpty(key))
                                    {
                                        key = propertyInfo.Name;
                                    }
                                    this.WriteObjectProperty(key, val,
                                                             () => {
                                        if (writeDelim)
                                        {
                                            this.WriteObjectPropertyDelim();
                                            //this.WriteLine();
                                        }
                                        else
                                        {
                                            writeDelim = true;
                                        }
                                    });
                                }
                            }
                        }
                    }
                }
                foreach (var fieldInfo in type.GetFields())
                {
                    if (fieldInfo.IsPublic && !fieldInfo.IsStatic)
                    {
                        if (!this.IsIgnored(type, fieldInfo, value))
                        {
                            object val = fieldInfo.GetValue(value);
                            if (!this.IsDefaultValue(fieldInfo, val))
                            {
                                string key = JsonNameAttribute.GetJsonName(fieldInfo);
                                if (string.IsNullOrEmpty(key))
                                {
                                    key = fieldInfo.Name;
                                }
                                this.WriteObjectProperty(key, val,
                                                         () => {
                                    if (writeDelim)
                                    {
                                        this.WriteObjectPropertyDelim();
                                        this.WriteLine();
                                    }
                                    else
                                    {
                                        writeDelim = true;
                                    }
                                });
                            }
                        }
                    }
                }
            } finally {
                depth--;
            }
            if (writeDelim)
            {
                this.WriteLine();
            }
            TextWriter.Write('}');
        }