1

java/kotlin devs , have you ever found yourself in a situation when the response from the api is having null for particular keys ( for eg say this is a response :{name :"Abc" ,age:12, role:null} ), you use a convertor for converting json to pojo, end up with null for that key, but really don't want that null, but rather a default value?

I had spent a lot of time with gson and moshi, but both seem to make me pull my hair. this is especially embarrassing when you are using kotlin which is known for being strict against nulls. thus the pojo class Person (written like this: data class Person( val name:String,val age:Int, val role:String) ) end up up with role== null when its clearly marked as a non null variable :''''(

Comments
  • 1
    This is why nearly everything I deserialize is Optional 😉 trust is low.
  • 0
    @SortOfTested you mean storing nulls in modal?
    Ugh i can't seem to find myself satisfied with this approach. if nulls are coming from the api, they are stored as nulls in the modal which will eventually get stored as null in some db somewhere.

    apps are usually powered by db data and most of the time we will have to specifically handle null cases for data. i don't like handling those cases and therefore store the messages directly in the modal (for eg my person.email should be directly returning either the email or "Sorry, the email of this user is not available"" , which is the exact same message displayed in the ui)
  • 4
    @2Large
    No, just typing the value as Optional in the record so that the null handling is mandatory. Jackson will take some value T and deserialize it into Optional.of(value).

    When dealing with external data, you oftentimes end up having to handle Byzantine faults.
  • 0
    Dunno if it's still the case:

    https://github.com/hsiafan/...

    But here's a module integrating optional instead of Null.

    Optional is a NULL wrapper introduced in Java 8

    https://baeldung.com/java-optional/
  • 0
    @2Large Idk about your framework, but if something isn't known then the only proper thing to put in the DB is a null, because the database can't mandate a specific way to handle nulls.
  • 0
    I don't understand the stigma of nulls. It just means absence of a value and has many many many uses. Also every real world api sucks and its bad so you just have to accept it and deal with it on conversion phase.
Add Comment