Converts an Enum to and from its name string value.
Inheritance: JsonConverter
 /// <summary>
 /// Enables indented camelCase for ease of reading.
 /// </summary>
 /// <param name="config">HttpConfiguration for this api</param>
 private static void EnableCamelCaseJson(HttpConfiguration config)
 {
     var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
     jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
     var stringEnumConverter = new StringEnumConverter { CamelCaseText = true };
     config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(stringEnumConverter);
     config.Formatters.JsonFormatter.Indent = true;
 }
Beispiel #2
0
        static JsonSettings()
        {
            var camelCaseEnums = new StringEnumConverter { CamelCaseText = true };

            Default = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                //ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
                //DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                NullValueHandling = NullValueHandling.Ignore,
                Formatting = Formatting.None,
                Converters = new List<JsonConverter> { camelCaseEnums }
            };
        }
        /// <summary>
        ///     Builds a HttpRequestMessage based on the options provided.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="file"></param>
        /// <param name="fileType"></param>
        /// <param name="config"></param>
        /// <param name="conversionTarget"></param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns></returns>
        internal HttpRequestMessage BuildRequestMessage(string url, Stream file, FileType fileType,
            ConversionTarget conversionTarget, JObject config = null)
        {
            if (string.IsNullOrWhiteSpace(url))
                throw new ArgumentNullException(nameof(url));

            if (file == null)
                throw new ArgumentNullException(nameof(file));

            if (config == null)
                config = new JObject();

            //Attach the conversion target to the config
            var jsonSerializer = new JsonSerializer();
            var stringEnumConverter = new StringEnumConverter();
            jsonSerializer.Converters.Add(stringEnumConverter);
            config["conversion_target"] = JToken.FromObject(conversionTarget, jsonSerializer);

            //Serialize the fileType and config to a string
            var serializedFileType =
                JsonConvert.SerializeObject(fileType, Formatting.None, stringEnumConverter).Replace("\"", "");
            var serializedConfig = config.ToString(Formatting.None, stringEnumConverter);

            var streamContent = new StreamContent(file);
            streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(serializedFileType);

            // ReSharper disable once ExceptionNotDocumented
            var content = new MultipartFormDataContent($"{DateTime.UtcNow.Ticks}")
            {
                {new StringContent(serializedConfig), "config"},
                {streamContent, nameof(file)}
            };

            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url)
            {
                Content = content
            };

            return httpRequestMessage;
        }
Beispiel #4
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            bool flag = ReflectionUtils.IsNullableType(objectType);
            Type type = flag ? Nullable.GetUnderlyingType(objectType) : objectType;

            if (reader.TokenType != JsonToken.Null)
            {
                try
                {
                    if (reader.TokenType == JsonToken.String)
                    {
                        string text = reader.Value.ToString();
                        object result;
                        if (text == string.Empty && flag)
                        {
                            result = null;
                            return(result);
                        }
                        BidirectionalDictionary <string, string> enumNameMap = this.GetEnumNameMap(type);
                        string value;
                        if (text.IndexOf(',') != -1)
                        {
                            string[] array = text.Split(new char[]
                            {
                                ','
                            });
                            for (int i = 0; i < array.Length; i++)
                            {
                                string enumText = array[i].Trim();
                                array[i] = StringEnumConverter.ResolvedEnumName(enumNameMap, enumText);
                            }
                            value = string.Join(", ", array);
                        }
                        else
                        {
                            value = StringEnumConverter.ResolvedEnumName(enumNameMap, text);
                        }
                        result = Enum.Parse(type, value, true);
                        return(result);
                    }
                    else if (reader.TokenType == JsonToken.Integer)
                    {
                        if (!this.AllowIntegerValues)
                        {
                            throw JsonSerializationException.Create(reader, "Integer value {0} is not allowed.".FormatWith(CultureInfo.InvariantCulture, reader.Value));
                        }
                        object result = ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, type);
                        return(result);
                    }
                }
                catch (Exception ex)
                {
                    throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.FormatValueForPrint(reader.Value), objectType), ex);
                }
                throw JsonSerializationException.Create(reader, "Unexpected token {0} when parsing enum.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }
            if (!ReflectionUtils.IsNullableType(objectType))
            {
                throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
            }
            return(null);
        }