Not sure if this is the right place to ask, as it ...
# announcements
i
Not sure if this is the right place to ask, as it involves a third party... But it's also related with the lang. I have a problem with Gson lib, that the api can send empty string as a date. I declared this adapter to tell Gson how to deserialize a date:
registerTypeAdapter(Date::class.java, DateDeserializer())
So when the object has a non optional
Date
, it's clear that I should throw an exception if it gets an empty string. But when
Date
is optional, I'd like to map the empty string to
null
, i.e. the date will just be assigned
null
. Not sure how to do that. It relates with lang, in that the deserializer is defined like this: `JsonDeserializer<Date>`but I need it to work with
Date?
basically. I can of course create a getter in my object that deserializes the date if present, but I'd like to do this directly with the parser, not "outside".
r
""
and
null
are not the same thing
i
that's exactly the point of my question
I have to treat
""
as
null
because the api is defective and it can't be fixed
trying out something
okay, it works by just changing the type of the deserializer to
JsonDeserializer<Date?>
(and returning
null
if it's an empty string)
Wait... this doesn't work. If I use non optional dates somewhere, and the api sends an empty string, I'd return
null
I need to be able to use a separate deserializer specifically for
Date?
.
d
Gson doesn't have a concept of nullable vs. not-nullable types. You would have to write a custom deserializer for the containing class (i.e. the class containing the
Date?
field).
i
ok, thanks! For now I ended using just a
String?
in my object and adding a computed variable to generate the
Date?
initially I didn't want to do this, because I had the date formatters in a singleton dependency and I can't pass it to the object, but ended moving them to an
object