Json.NET StringEnumConverter无法按预期工作

Gar*_*and 16 c# serialization json json.net

I'm attempting to use Json.NET with the System.Net.Http.HttpClient to send an object with an enum property, however the enum is always serialized as an integer value rather than the string equivalent.

I've tried following the instructions here:

http://james.newtonking.com/archive/2013/05/08/json-net-5-0-release-5-defaultsettings-and-extension-data

By both adding an instance of StringEnumConverter to the JsonSerializerSettings and also tried to decorate the enum property with [JsonProperty(ItemConverterType = typeof(StringEnumConverter))] neither of which appear to be working in my example.

I'm using Json.NET version 5.0.8

Can anyone tell me what I'm doing wrong please? Here is a sample console app to replicate showing both the global serializer settings and the decorated property:

Thanks.

using System;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpClient client = new HttpClient { BaseAddress = new Uri("http://test-uri.com") };

            JsonConvert.DefaultSettings = (() =>
            {
                var settings = new JsonSerializerSettings();
                settings.Converters.Add(new StringEnumConverter());
                return settings;
            });

            var data = new TestData { Enum = TestEnum.Hello };

            // The following posts: {"Enum":0}
            // Shouldn't it post {"Enum":"Hello"} instead?
            var result = client.PostAsJsonAsync("/test", data).Result;
        }

        public class TestData
        {
            [JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
            public TestEnum Enum { get; set; }
        }

        public enum TestEnum
        {
            Hello,
            World
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我和Fiddler一起检查了这个问题并发布了帖子:{"Enum":0}而不是{"Enum":"Hello"}我期望的那样.

Jef*_*ado 23

ItemConverterType该财产JsonPropertyAttribute属性是用于收集的物品转换器.您应该使用该JsonConverterAttribute属性.

public class TestData
{
    [JsonConverter(typeof(StringEnumConverter))]
    public TestEnum Enum { get; set; }
}
Run Code Online (Sandbox Code Playgroud)


Gar*_*and 9

我想我已经找到了一种在没有装饰属性的情况下让它工作的方法.它涉及到更换client.PostAsJsonAsync()client.PostAsync().然后,您可以指定要使用的MediaTypeFormatter,在这种情况下将是JsonMediaTypeFormatter.

来源:.net HttpClient与自定义JsonConverter

    var settings = new JsonSerializerSettings();
    settings.Converters.Add(new StringEnumConverter());
    var formatter = new JsonMediaTypeFormatter { SerializerSettings = settings };
    var response = client.PostAsync("/test", data, formatter).Result;
Run Code Online (Sandbox Code Playgroud)

这仍然无法解释为什么没有应用DefaultSettings.我只能假设[JsonConverter]属性的存在迫使HttpClient使用Json.NET进行序列化,否则它只使用默认的序列化程序.

  • 不应用DefaultSettings,因为`PostAsJsonAsync`调用`new JsonMediaTypeFormatter()`,它创建`JsonSerializerSettings`的新实例并绕过默认设置.这是错误和烦人的. (8认同)