22

The Client side receives a formal JSON content "{\"Id\":[1,2,3],\"Size\":56}", but get an error in deserialization the byte array.

1 Error occurs in the statement below

IRestResponse<key> response = client.Execute<key>(request);

2 Error message is "No parameterless constructor defined for this object."

3 The object class in client size is the same as it's in server side:

public class key
{
    public byte[] id { get; set; }
    public int Size { set; get; }
}

4 I've tried passing object that contains string and integer by JSON format and that's all fine but byte array.

Josh
  • 999
  • 3
  • 15
  • 31
Yan Zhengshan
  • 221
  • 1
  • 2
  • 4

3 Answers3

53

JsonDeserializer from RestSharp can not deserialize array. Instead of byte[] use List<byte>. For more information see https://github.com/restsharp/RestSharp/wiki/Deserialization

user3111679
  • 531
  • 4
  • 3
  • 2
    This happened to me as well, I finally figured out I had left a pesky string array laying around in one of my classes. Changing it to a List fixed the problem immediately and all tests started passing. – jamesbar2 Nov 04 '15 at 16:34
26

I have run into this issue, too. My solution was to use RestSharp to perform a raw execute and use Json.NET to deserialize the result:

var response = client.Execute(request);
var keyResponse = JsonConvert.DeserializeObject<key>(response.Content);

keyResponse should now be an instance of your key class deserialized from the JSON content.

Chris Hogan
  • 868
  • 6
  • 9
0

In addition to Chris Hogan's reply, I'd like to point out that I got this error when RestSharp incorrectly used the default serializer instead of the custom JSON.NET serializer I had assigned.

The reason for this was that I added a handler with content type application/json whereas the API I was getting the response from returned the content as text/json.

So by changing the AddHandler call to AddHandler("text/json", jsonDeserializer), I resolved the issue.

silkfire
  • 20,433
  • 12
  • 70
  • 93