square / moshi

A modern JSON library for Kotlin and Java.
https://square.github.io/moshi/1.x/
Apache License 2.0
9.76k stars 760 forks source link

Hook for detecting when default value is used for EnumJsonAdapter #845

Closed justintuchek closed 5 years ago

justintuchek commented 5 years ago

Hey 👋

Wanted to put up a proposal for a modification to EnumJsonAdapter

It'd be great to be notified when the default value is used and what the key was that was unable to be mapped so it can be updated.

Here are a few things that came to mind where the name could be provided back to the consumer for reporting:

fun withUnknownFallback(fallbackValue T?, fallbackConsumed: (String) -> Unit): EnumJsonAdapter<T> {
  return EnumJsonAdapter(enumType, fallbackValue, fallbackConsumed, true);
}
fun withUnknownFallback(fallback: (String) -> T?): EnumJsonAdapter<T> {
  return EnumJsonAdapter(enumType, fallback, true);
}

In use:

enum class Shape {
  Square,
  Circle,
  Undefined
}

EnumJsonAdapter.create(Shape::class.java)
  .withUnknownFallback { name -> // Client doesn't yet have support for "squircle"
    Timber.e("Detected new shape of: $name")
    Undefined
  }

I know the implementation isn't currently in Kotlin, was easier to sketch out the changes. If this is something that seems like a good idea I'd be more than willing to open an PR!

swankjesse commented 5 years ago

If you want this, you should write your own enum adapter!

justintuchek commented 5 years ago

Think that's fair and definitely doable 👍

Maybe only specific to our use case but wanted to offer upstream if there was a chance to contribute back. Thanks Jesse!