我正在使用RestSharp來使用REST Web服務。我已經實現了自己的Response對象類,用於在RestSharp中集成的自動序列化/反序列化。RestSharp無法正確反序列化JSON
我也添加了一個映射與枚舉,正常工作。
這一類的問題是,當我發送一個正確的請求我得到一個正確的響應,所以Response.Content包含我所期望的,但反序列化過程中不能正常工作。
Response.Content
{
"resultCode": "SUCCESS",
"hub.sessionId": "95864537-4a92-4fb7-8f6e-7880ce655d86"
}
的ResultCode
屬性是正確映射到ResultCode.SUCCESS
枚舉值,但HubSessionId
屬性始終是null
所以看起來它不反序列化。
我看到的唯一可能的問題是帶有'。'的JSON PropertyName。在名字裏。這可能是問題嗎?這是否與不是Newtonsoft.Json的新JSON序列化程序相關?我該如何解決它?
UPDATE
我發現,JSON的屬性被完全地忽略,所以也[JsonConverter(typeof(StringEnumConverter))]
。因此我認爲枚舉映射是由默認序列化器自動執行的,沒有任何屬性。 「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的問題。我可以這樣說,因爲最老的和最新的兩個版本都可以與你的JSON樣本一起工作。看小提琴。 https://dotnetfiddle.net/i0zmc0它使用v3.5.x.你也可以試試8.x。 – niksofteng
我會添加一些關於我的代碼的更多細節。 –
'JsonProperty'是一個Json.NET屬性。如果序列化程序不是Json.NET,則JsonProperty屬性將被忽略。 * new * serializer的等價屬性是什麼? –