2

我有以下使用 RestSharp 调用 Web 服务的代码。代码运行没有错误,但是当我查看 response.Data 时,我看到 Result 对象没有反序列化,并且仍然包含默认值。

<Serializable()> <DataContract()> _
Private Class Result
  <DataMember(IsRequired:=False)> _
  Public responseCode As Long
  <DataMember(IsRequired:=False)> _
  Public responseMessage As String
  Friend Const RESULT_OK As Long = 2000
End Class

Private Function Login(ByVal user As String, ByVal password As String) As  RestResponseCookie
  Dim req As New RestRequest("authenticationService/authentication/signIn", Method.POST)
  req.RequestFormat = DataFormat.Json
  Dim input As New SigninInput
  input.requestParameters.username = user
  input.requestParameters.password = password
  req.AddBody(input)

  Dim response As RestResponse(Of Result) = getRestClient().Execute(Of Result)(req)
  If response.StatusCode = HttpStatusCode.OK Then
    Dim res As Result = response.Data
  End If
  Return Nothing
End Function

现在,如果我将代码更改为以下内容:

  Dim response As RestResponse = getRestClient().Execute(req)
  If response.StatusCode = HttpStatusCode.OK Then
    Dim des As New Json.DataContractJsonSerializer(GetType(Result))
    Dim res As Result = CType(des.ReadObject(New IO.MemoryStream(response.RawBytes)), Result)
  End If

反序列化运行得很好。我尝试从代码的非工作版本中调试结果,并且内容似乎很好。这是我得到的内容: "{"responseMessage":"Success: Your request was successfully completed.","re​​sponseCode":2000}" 并且 ContentType 应该是“application/json”。

我可以运行有效的代码,但我很高兴知道为什么 RestSharp 的反序列化没有正确进行。

4

1 回答 1

1

RestSharp 不会反序列化为字段,您必须将它们更改为属性,然后它应该可以工作。

于 2012-05-16T17:38:55.150 回答