我正在使用RestSharp来使用REST Web服务。我已经实现了自己的Response对象类,以与集成在RestSharp中的自动序列化/反序列化一起使用。
我还添加了带有枚举的映射,该枚举可以正常工作。
此类的问题是,当我发送正确的请求时,我返回了正确的响应,因此Response.Content包含了我所期望的内容,但是反序列化过程无法正常工作。
响应。内容
{
"resultCode": "SUCCESS",
"hub.sessionId": "95864537-4a92-4fb7-8f6e-7880ce655d86"
}
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;
}
最佳答案
在 Newtonsoft的JSON.NET 情况下,使用自定义JSON Serializer
和Deserializer
解决。
我遵循了Philipp Wagner在article中解释的步骤。
我还注意到,使用默认Request
序列化Serializer
不能像枚举预期的那样工作。它没有序列化枚举字符串值,而是放置了枚举int值,该值取自我的枚举定义。
使用JSON.NET现在,序列化和反序列化过程可以正常工作。
关于c# - RestSharp无法正确反序列化JSON,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38591048/