0

Im using restsharp 105.2.3 and I have a model class's property (CalcDate) bound to a DateTime type but I am using a converter to parse the incoming rest response to build the timestamp. This works well, unless the svc doesn't return "calcDate"; When it's missing, the model fails to deserialized. The error that i get from IRestResponse.ErrorMessage is:

"Value to add was out of range.\r\nParameter name: value"

Interestingly if I use the raw json (with the missing calcDate) and try to construct it using jsonConvert, then it works as expected and the model is built with nulled calcDate.

> Newtonsoft.Json.JsonConvert.DeserializeObject<MyModel>(json) // works

Code:

public class MyModel {

        [JsonProperty("id")]
        public int Id { get; set; }

        [JsonConverter(typeof(TimestampConverter))]
        [JsonProperty("calcDate")]
        public DateTime? CalcDate { get; set; }
}

public class TimestampConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jvalue = JValue.Load(reader);
            if (jvalue.Type == JTokenType.String)
            {
                long val = 0;
                if (long.TryParse(jvalue.ToString(), out val)) {
                    DateTimeOffset dto = DateTimeOffset.FromUnixTimeMilliseconds(Convert.ToInt64(val));

                    return dto.DateTime;
                }
            }

            return DateTime.MinValue;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }

Question: How can i make restsharp use jsonConvert to deserialize the json?

JensG
  • 13,148
  • 4
  • 45
  • 55
webber
  • 1,834
  • 5
  • 24
  • 56
  • RestSharp doesn't use Json.NET by default. See http://restsharp.org/ and https://github.com/restsharp/RestSharp/blob/master/readme.txt: **In 103.0, JSON.NET was removed as a dependency.** – dbc Jan 17 '17 at 22:34
  • 1
    See [RestSharp serialization to JSON, object is not using SerializeAs attribute as expected](http://stackoverflow.com/q/21633649/3744182) and maybe http://bytefish.de/blog/restsharp_custom_json_serializer/ or https://github.com/adamfisher/RestSharp.Newtonsoft.Json to switch back. – dbc Jan 17 '17 at 22:42

0 Answers0