RestSharp对Enum类型的属性进行反序列化

Abd*_*mon 4 c# restsharp

我有一个对象

            var testTcc = new TrendingConfigurationConfigDto
            {
                TrendingConfigurationId =1,
                ConfigId = 1,
                DeviceId = 1,
                Selected = true,
                YAxisPosition = YAxisPosition.Left,
                Order = 1,
                Color = "#ffffff",
                Configuration = new BO.Shared.Dtos.List.ConfigurationListDto
                {
                    Id = 1,
                    Name = "configuration",
                    Alias = "configuationAlias",
                    EnableEdit = true,
                    IsBusinessItem = true
                },
                Device = new BO.Shared.Dtos.List.DeviceListDto
                {
                    Id = 1,
                    Name = "Device"
                }
            };
Run Code Online (Sandbox Code Playgroud)

当我将其序列化为json时

var jsonTcc = SimpleJson.SerializeObject(testTcc);
Run Code Online (Sandbox Code Playgroud)

它返回的字符串包含YAxisPosition = 1的json对象,当我尝试使用

testTcc = SimpleJson.DeserializeObject<TrendingConfigurationConfigDto>(jsonTcc);
Run Code Online (Sandbox Code Playgroud)

它给出异常System.InvalidCastException,并显示消息“指定的转换无效”。

我尝试将json字符串中的YAxisPosition值更改为字符串“ 1”或“ Left”,这总是给我相同的错误,直到我从json字符串中删除了属性YAxisPosition。

我可能缺少一些东西(枚举属性上的Attribute或类似的东西)。

请帮助我找到一种方法,以便我可以使用RestSharp对包含Enum类型属性的对象进行序列化和反序列化。

注意:我尝试使用NewtonSoft成功进行序列化和反序列化。但是我不希望Web API客户端依赖NetwonSoft,因为我已经在使用RestSharp。

Ada*_*dam 6

RestSharp在v103.0中删除了JSON.NET支持。默认的Json序列化器不再与Json.NET兼容。如果要继续使用JSON.NET并保持向后兼容性,则有两种选择。除此之外,JSON.NET还具有更多功能,并且可以通过使用RestSharp现在依赖的基本.NET序列化程序解决您的问题。

另外,您可以使用[EnumMember]属性在反序列化期间定义自定义映射。

选项1:实施使用JSON.NET的自定义序列化程序

要使用Json.NET进行序列化,请复制以下代码:

/// <summary>
/// Default JSON serializer for request bodies
/// Doesn't currently use the SerializeAs attribute, defers to Newtonsoft's attributes
/// </summary>
public class JsonNetSerializer : ISerializer
{
    private readonly Newtonsoft.Json.JsonSerializer _serializer;

    /// <summary>
    /// Default serializer
    /// </summary>
    public JsonSerializer() {
        ContentType = "application/json";
        _serializer = new Newtonsoft.Json.JsonSerializer {
            MissingMemberHandling = MissingMemberHandling.Ignore,
            NullValueHandling = NullValueHandling.Include,
            DefaultValueHandling = DefaultValueHandling.Include
        };
    }

    /// <summary>
    /// Default serializer with overload for allowing custom Json.NET settings
    /// </summary>
    public JsonSerializer(Newtonsoft.Json.JsonSerializer serializer){
        ContentType = "application/json";
        _serializer = serializer;
    }

    /// <summary>
    /// Serialize the object as JSON
    /// </summary>
    /// <param name="obj">Object to serialize</param>
    /// <returns>JSON as String</returns>
    public string Serialize(object obj) {
        using (var stringWriter = new StringWriter()) {
            using (var jsonTextWriter = new JsonTextWriter(stringWriter)) {
                jsonTextWriter.Formatting = Formatting.Indented;
                jsonTextWriter.QuoteChar = '"';

                _serializer.Serialize(jsonTextWriter, obj);

                var result = stringWriter.ToString();
                return result;
            }
        }
    }

    /// <summary>
    /// Unused for JSON Serialization
    /// </summary>
    public string DateFormat { get; set; }
    /// <summary>
    /// Unused for JSON Serialization
    /// </summary>
    public string RootElement { get; set; }
    /// <summary>
    /// Unused for JSON Serialization
    /// </summary>
    public string Namespace { get; set; }
    /// <summary>
    /// Content type for serialized content
    /// </summary>
    public string ContentType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并向您的客户注册:

var client = new RestClient();
client.JsonSerializer = new JsonNetSerializer();
Run Code Online (Sandbox Code Playgroud)

选项2:使用nuget包使用JSON.NET

无需执行所有这些操作,而是在整个项目中分布自定义JSON序列化程序,而只需使用以下nuget软件包:https ://www.nuget.org/packages/RestSharp.Newtonsoft.Json 。它允许您使用继承的RestRequest对象,该对象默认内部使用Newtonsoft.JSON,如下所示:

var request = new RestSharp.Newtonsoft.Json.RestRequest(); // Uses JSON.NET
Run Code Online (Sandbox Code Playgroud)

另一个选择是在每个请求上都设置如下:

var request = new RestRequest();
request.JsonSerializer = new NewtonsoftJsonSerializer();
Run Code Online (Sandbox Code Playgroud)

免责声明:我对在项目中放置自定义序列化程序感到沮丧后创建了这个项目。我创建此程序的目的是为了保持环境整洁,并希望能帮助希望与v103之前的RestSharp代码向后兼容的其他人。