Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Very unclear "Nesting Problem" error #806

Open
foxfriends opened this issue Feb 12, 2019 · 0 comments
Open

Very unclear "Nesting Problem" error #806

foxfriends opened this issue Feb 12, 2019 · 0 comments
Milestone

Comments

@foxfriends
Copy link

Though admittedly the reason an exception was thrown was my own fault, there was not actually a problem with nesting as the message would have me believe, but rather I had implemented a JsonAdapter that did not actually write any value, and then KotlinJsonAdapter continued to try and write other entries.

Here is some code that causes this situation.

sealed class MyType {
  data class MyInt(val int: Int): MyType()
  data class MyString(val string: String): MyType()
}

data class MyContainer(
  val value: MyType?,
  val otherValue: Int
)

object MyAdapter: JsonAdapter<MyType>() {
  @ToJson
  override fun toJson(writer: JsonWriter, request: MyType?) {
    when (request) {
      is MyType.MyInt -> writer.value(request.int)
      is MyType.MyString -> writer.value(request.string)
      // whoops I forgot to handle the null case!
    }
  }

  @FromJson
  override fun fromJson(reader: JsonReader): MyType? {
    TODO("Not relevant")
  }
}

val converter = Moshi.Builder()
  .add(MyAdapter)
  .add(KotlinJsonAdapterFactory())
  .build()

val container = MyContainer(null, 3)

val json = converter
  .adapter(MyContainer::class.java)
  .toJson(container) // Uh oh... Nesting problem!

I think this case is one where it would be preferable to fail earlier, and show a more meaningful error message to the user, such as the "Dangling name: __" one you would get if the MyContainer type did not have a second val in it. This could save someone else in this situation lot of unneeded debugging!

Here is KotlinJsonAdapter where the problem is encountered.

  override fun toJson(writer: JsonWriter, value: T?) {
    if (value == null) throw NullPointerException("value == null")

    writer.beginObject()
    for (binding in bindings) {
      if (binding == null) continue // Skip constructor parameters that aren't properties.

      writer.name(binding.name)
      binding.adapter.toJson(writer, binding.get(value))
      // Suggestion: detect if a value as not actually been written around here
      //   and throw an exception!
      // Alternatively, just use a better error message in the Writer implementation
      //   when deferredName is not null
    }
    writer.endObject()
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants