Implemented custom duplicate key handling

- Supports: throw an exception (by default), ignore, overwrite & merge into a JSONArray
 - With tests, 4/4 passed.
This commit is contained in:
XIAYM-gh
2024-02-13 18:56:10 +08:00
parent 010e83b925
commit 10514e48cb
4 changed files with 191 additions and 34 deletions

View File

@@ -4,23 +4,47 @@ package org.json;
* Configuration object for the JSON parser. The configuration is immutable.
*/
public class JSONParserConfiguration extends ParserConfiguration {
/**
* The way should be used to handle duplicate keys.
*/
private JSONDuplicateKeyStrategy duplicateKeyStrategy;
/**
* Configuration with the default values.
*/
public JSONParserConfiguration() {
super();
}
/**
* Configuration with the default values.
*/
public JSONParserConfiguration() {
this(JSONDuplicateKeyStrategy.THROW_EXCEPTION);
}
@Override
protected JSONParserConfiguration clone() {
return new JSONParserConfiguration();
}
/**
* Configure the parser with {@link JSONDuplicateKeyStrategy}.
*
* @param duplicateKeyStrategy Indicate which way should be used to handle duplicate keys.
*/
public JSONParserConfiguration(JSONDuplicateKeyStrategy duplicateKeyStrategy) {
super();
this.duplicateKeyStrategy = duplicateKeyStrategy;
}
@SuppressWarnings("unchecked")
@Override
public JSONParserConfiguration withMaxNestingDepth(final int maxNestingDepth) {
return super.withMaxNestingDepth(maxNestingDepth);
}
@Override
protected JSONParserConfiguration clone() {
return new JSONParserConfiguration();
}
@SuppressWarnings("unchecked")
@Override
public JSONParserConfiguration withMaxNestingDepth(final int maxNestingDepth) {
return super.withMaxNestingDepth(maxNestingDepth);
}
public JSONParserConfiguration withDuplicateKeyStrategy(final JSONDuplicateKeyStrategy duplicateKeyStrategy) {
JSONParserConfiguration newConfig = this.clone();
newConfig.duplicateKeyStrategy = duplicateKeyStrategy;
return newConfig;
}
public JSONDuplicateKeyStrategy getDuplicateKeyStrategy() {
return this.duplicateKeyStrategy;
}
}