RestSharp无法正确反序列化JSON

Che*_*Cat 3 c# rest serialization json restsharp

我正在使用RestSharp来使用REST Web服务。我实现了自己的Response对象类,以与RestSharp中集成的自动序列化/反序列化一起使用。

我还添加了一个可以正常工作的枚举映射。

此类的问题是,当我发送正确的请求时,我会返回正确的响应,因此Response.Content包含了我期望的内容,但是反序列化过程无法正常工作。

响应内容

{
    "resultCode": "SUCCESS",
    "hub.sessionId": "95864537-4a92-4fb7-8f6e-7880ce655d86"
}
Run Code Online (Sandbox Code Playgroud)

ResultCode属性已正确映射到ResultCode.SUCCESS枚举值,但该HubSessionId属性始终为,null因此似乎未进行反序列化。

我看到的唯一可能的问题是带有'。'的JSON PropertyName。在名字里。可能是问题吗?这与不是Newtonsoft.Json的新JSON序列化程序有关吗?我该如何解决?

更新

我发现Json Attributes被完全忽略,[JsonConverter(typeof(StringEnumConverter))]。因此,我认为枚举映射由默认的Serializer自动执行,没有任何属性。“ hub.sessionId”属性的问题仍然存在。

这是我的代码

public class LoginResponse
{
    [JsonProperty(PropertyName = "resultCode")]
    [JsonConverter(typeof(StringEnumConverter))]
    public ResultCode ResultCode { get; set; }

    [JsonProperty(PropertyName = "hub.sessionId")]
    public string HubSessionId { get; set; }
}

public enum ResultCode
{
    SUCCESS,
    FAILURE
}

// Executes the request and deserialize the JSON to the corresponding
// Response object type.
private T Execute<T>(RestRequest request) where T : new()
{
    RestClient client = new RestClient(BaseUrl);

    request.RequestFormat = DataFormat.Json;

    IRestResponse<T> response = client.Execute<T>(request);

    if (response.ErrorException != null)
    {
        const string message = "Error!";
        throw new ApplicationException(message, response.ErrorException);
    }

    return response.Data;
}

public LoginResponse Login()
{
    RestRequest request = new RestRequest(Method.POST);
    request.Resource = "login";
    request.AddParameter("username", Username, ParameterType.GetOrPost);
    request.AddParameter("password", Password, ParameterType.GetOrPost);
    LoginResponse response = Execute<LoginResponse>(request);
    HubSessionId = response.HubSessionId; // Always null!
    return response;
}
Run Code Online (Sandbox Code Playgroud)

Che*_*Cat 5

使用自定义JSON解决Serializer,并Deserializer在案件Newtonsoft的JSON.NET。我遵循了Philipp Wagner 在本文中解释的步骤。

我还注意到,Request使用默认值对a 进行序列化Serializer无法像枚举预期的那样工作。它没有序列化枚举字符串值,而是放置了从我的枚举定义中获取的枚举int值。

现在,使用JSON.NET,序列化和反序列化过程可以正常工作。