From 2805717dedd5106c0d91a3829d01ea747aaadc5a Mon Sep 17 00:00:00 2001 From: DBotThePony Date: Sat, 31 Dec 2022 13:25:11 +0700 Subject: [PATCH] extraPropertiesAreFatal --- .../kstarbound/io/json/BuilderAdapter.kt | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/ru/dbotthepony/kstarbound/io/json/BuilderAdapter.kt b/src/main/kotlin/ru/dbotthepony/kstarbound/io/json/BuilderAdapter.kt index 2604e120..4307172c 100644 --- a/src/main/kotlin/ru/dbotthepony/kstarbound/io/json/BuilderAdapter.kt +++ b/src/main/kotlin/ru/dbotthepony/kstarbound/io/json/BuilderAdapter.kt @@ -44,6 +44,11 @@ class BuilderAdapter private constructor( * Ключи, которые необходимо игнорировать при чтении JSON */ val ignoreKeys: ImmutableSet, + + /** + * @see Builder.extraPropertiesAreFatal + */ + val extraPropertiesAreFatal: Boolean, ) : TypeAdapter() { private val loggedMisses = ObjectOpenHashSet() @@ -87,6 +92,10 @@ class BuilderAdapter private constructor( throw JsonSyntaxException("Reading property ${property.name} of ${instance::class.qualifiedName} near ${reader.path}", err) } } else { + if (extraPropertiesAreFatal) { + throw JsonSyntaxException("$name is not a valid property of ${instance::class.qualifiedName}") + } + if (!loggedMisses.contains(name)) { LOGGER.warn("{} has no property for storing {}", instance::class.qualifiedName, name) loggedMisses.add(name) @@ -160,6 +169,18 @@ class BuilderAdapter private constructor( class Builder(val factory: () -> T, vararg fields: KMutableProperty1) { private val properties = ArrayList>() private val ignoreKeys = ObjectArraySet() + var extraPropertiesAreFatal = false + + /** + * Являются ли "лишние" ключи в JSON структуре ошибкой. + * + * Если "лишние" ключи являются ошибкой и известны некоторые лишние ключи, которые не нужны, + * то [extraPropertiesAreFatal] можно скомбинировать с [ignoreKey]. + */ + fun extraPropertiesAreFatal(flag: Boolean = true): Builder { + extraPropertiesAreFatal = flag + return this + } init { for (field in fields) @@ -216,7 +237,12 @@ class BuilderAdapter private constructor( for (property in properties) map.put(property.property.name, property) - return BuilderAdapter(factory, map.build(), ImmutableSet.copyOf(ignoreKeys)) + return BuilderAdapter( + factory = factory, + properties = map.build(), + ignoreKeys = ImmutableSet.copyOf(ignoreKeys), + extraPropertiesAreFatal = extraPropertiesAreFatal, + ) } }