I have an enum that represents the various different types of errors i could get for a particular server endpoint. If i get back a value that isn鈥檛 in that enum (say, the server adds a new error type and I鈥檓 on an old client that doesn鈥檛 know about it), EnumJsonAdapter blows up. I'd like to add an option to have it just return null in that case. Thoughts? How would I go about adding this? (I don't see any customization of the StandardJsonAdapters but I might just be missing it)
Or is the answer just "add your own enum adapter Factory"?
That's the easiest. We should probably include that as a standard extra adapter.
Cool, I'll just roll my own for now, thanks!
Sorry for bragging, but there is a @FallbackEnum annotation in a small extension I've wrote. It allows to specify a fallback value (spares a null check). The used adapter is a fork of the internal one.
@edenman and everybody else,
Is this okay to close, given the above sample? Is it alright not to have this fallback in the JsonAdapter API?
I'm ok with the "roll your own"/"use the sample" approach, but it does still seem like something that is a common enough occurrence that it'd be good to build in (at least as an option). Not a big deal either way though, I'm already using my own bespoke adapter.
Yep. I think we want something specifically for enums.
FWIW I currently roll my own "enum fallback adapters". Would love to see this get added.
@swankjesse Are you thinking something like Moshi.Builder.add(Class<T> enumType, T defaultValue)? That would be trivial to implement, but maybe there's a better API I'm not thinking of yet.
Or, Builder.enumFallback(T fallbackValue) and skip the class parameter?
You wouldn't be able to fall back to null, then, but that might be okay. Force people who need a fallback to define a default or a special "UNKNOWN" type instead of null.
Done in #607. An EnumJsonAdapter will be in the adapters artifact in the next release.
Most helpful comment
Sorry for bragging, but there is a
@FallbackEnumannotation in a small extension I've wrote. It allows to specify a fallback value (spares a null check). The used adapter is a fork of the internal one.