0

I have a json string that comes back as:

{ "expires_in": 300 }

I defined a class:

class Test
{
   public DateTime ExpirationDate {get;set;}
}

Now I want to deserialize into that object, but want to convert the 300 to mean DateTime.Now.AddSeconds(300) so I did:

JsonConvert.DeserializeObject<Test>("{ \"expires_in\": 300 }");

So I tried:

class Test
{
   [JsonProperty("expires_in", ItemConverterType=typeof(TestConverter))]
   public DateTime ExpirationDate {get;set;}
}

But it never seems to get into the converter. Am I missing something?

Converter is just stubbed out:

class TestConvert : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
SledgeHammer
  • 7,338
  • 6
  • 41
  • 86
  • Could you please share your `TestConverter`? – Minijack Nov 28 '18 at 23:04
  • @Minijack Added, but its just stubbed out right now. None of those are getting hit. – SledgeHammer Nov 28 '18 at 23:06
  • if `CanConvert` does not return true then it will not try and convert the value – Minijack Nov 28 '18 at 23:08
  • @Minijack it doesn't even get into any of those methods... – SledgeHammer Nov 28 '18 at 23:08
  • try `JsonConvert.DeserializeObject("{ \"expires_in\": 300 }", new TestConvert());` – Minijack Nov 28 '18 at 23:09
  • @Minijack when I do that, it gets into it for the Test object. Isn't it supposed to do it for each property that has the converter on it? – SledgeHammer Nov 28 '18 at 23:15
  • use `Converter` rather then `ItemConverter` as `ItemConverter` is for collections, see [docs](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Serialization_JsonProperty.htm) – Minijack Nov 28 '18 at 23:24
  • @Minijack Yeah, I had to change to [JsonProperty("expires_in")] [JsonConverter(typeof(TestConverter))] public DateTime ExpirationDate { get; set; } to get it to work. Can't do it with a single attribute I guess. Thanks! – SledgeHammer Nov 28 '18 at 23:29
  • Seems like a duplicate of [Why serializing Version with JsonPropertyAttribute doesn't work?](https://stackoverflow.com/a/38319910/3744182) and/or [Proper way of using Newtonsoft Json ItemConverterType](https://stackoverflow.com/a/24640305/3744182). – dbc Nov 28 '18 at 23:41

0 Answers0