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)
| 归档时间: |
|
| 查看次数: |
6209 次 |
| 最近记录: |