我正在使用RestSharp来调用REST Web服务。我已经实现了自己的响应对象类,用于与RestSharp集成的自动序列化/反序列化一起使用。
我还添加了一个枚举映射,它可以正常工作。
这个类的问题是,当我发送一个正确的请求时,我会收到一个正确的响应,所以Response.Content包含我期望的内容,但反序列化过程不起作用。
Response.Content:
我唯一可能看到的问题是JSON PropertyName中包含'.'。这可能是问题吗?这与不再是Newtonsoft.Json的新JSON Serializer有关吗?如何解决它? 更新 我发现Json Attributes完全被忽略了,因此也忽略了
我还添加了一个枚举映射,它可以正常工作。
这个类的问题是,当我发送一个正确的请求时,我会收到一个正确的响应,所以Response.Content包含我期望的内容,但反序列化过程不起作用。
Response.Content:
{
"resultCode": "SUCCESS",
"hub.sessionId": "95864537-4a92-4fb7-8f6e-7880ce655d86"
}
ResultCode
属性正确映射到ResultCode.SUCCESS
枚举值,但HubSessionId
属性始终为null
,似乎没有被反序列化。我唯一可能看到的问题是JSON PropertyName中包含'.'。这可能是问题吗?这与不再是Newtonsoft.Json的新JSON Serializer有关吗?如何解决它? 更新 我发现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;
}
[JsonConverter(typeof(StringEnumConverter))]
属性,它可以正常工作,因为映射到我的枚举类是正确的。2)我尝试使用[DeserializeAs(Name = "hub.sessionId")]
属性,就像在RestSharp Wiki中建议的那样,但它也不起作用。 - Cheshire Cat