Skip to content

Proposal: Add option getOptions(): JsonReader.Options function to JsonAdapter. #1296

@ZacSweers

Description

@ZacSweers

This would allow easy querying of what properties an adapter intends to read, unlocking the ability to easily track unknown properties.

abstract class JsonAdapter<T> {
  /** Returns the available Options this adapter looks for in parsing. Null if undefined. */
  val options: JsonReader.Options? = null
}

class MyRecordingFactory : JsonAdapter.Factory {
  override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*> {
    // Look for some opt-in
    if (type is Class<*> && type.isAnnotationPresent(TrackUnknownProperties::class.java) {
      val delegate = moshi.nextAdapter<Any>(this, type, annotations)
      val options = delegate.options?.strings()?.toSet() ?: return delegate
      return object : JsonAdapter<Any> {
        override fun fromJson(reader: JsonReader): Any {
          val jsonValue = reader.readJsonValue() as Map<String, *>
          val unknownKeys = jsonValue.keys.filterNot { it in options }
          if (unknownKeys.isNotEmpty()) {
            // Report unknown keys!
          }
          
          return delegate.fromJsonValue(jsonValue
        }
      }
    }
  }
}

If we don't want this as a dedicated API, we could also make it a special-cased subclass

abstract class OptionsJsonAdapter<T> : JsonAdapter<T>() {
  /** Returns the available Options this adapter looks for in parsing. Null if undefined. */
  val options: JsonReader.Options? = null
}

Or we could remove options from the API entirely and make it simple strings

abstract class JsonAdapter<T> {
  /** Returns the available names this adapter looks for in parsing. Null if undefined. */
  val names: Set<String>? = null
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions