Dealing with empty object from API service
Hi, what is the best to handle when we got name: {} (this is from nodejs backend) response from api service, meanwhile what i want is to assume it is 'name: {first: "", last: ""}` so I can parse it to
Person {firstName :: Maybe Text, lastName :: Maybe Text} ?
supposed that I have the following types: https://gist.github.com/Rizary/3b3865a145853cf04df7fad4e348a5c3
I finally use optional but actually that's not what I want, because I can't parsed the name: {} as name: {first: "", last: ""}
Sorry for the late reply!
What I'd probably do here is to have one type for deserialization, Person { first :: Maybe Text, last :: Maybe Text } and then provide a total conversion into another type Person2 { first :: Text, last :: Text }. If you want to be fancier you can have just one type data Person f = Person { first :: f Text, last :: f Text }, parse Person Maybe, and provide a conversion Person Maybe -> Person Identity. I doubt that extra complexity is worthwhile though...
If you want to write the FromJSON instance manually instead I think you can use (.:?) to parse the fields and you'll get a Parser (Maybe Text) that you can fmap into a Parser Text.
Do you think that will work, or did you already solve it?
Hi @bergmark thanks for your answer. I will try it and get back to you.