json序列化时,增加允许多个相同的key配置

This commit is contained in:
zhangrenhua
2022-07-22 09:04:33 +08:00
parent 0ca9627663
commit 4eb720bb31
3 changed files with 36 additions and 1 deletions

View File

@@ -44,6 +44,11 @@ public class JSONConfig implements Serializable {
*/
private boolean stripTrailingZeros = true;
/**
* 是否忽略多个相同的key
*/
private boolean ignoreDuplicateKey = false;
/**
* 创建默认的配置项
*
@@ -235,4 +240,22 @@ public class JSONConfig implements Serializable {
this.stripTrailingZeros = stripTrailingZeros;
return this;
}
/**
* 是否忽略多个相同的key
* @return
*/
public boolean isIgnoreDuplicateKey() {
return ignoreDuplicateKey;
}
/**
* 是否忽略多个相同的key
* @param ignoreDuplicateKey
* @return
*/
public JSONConfig setIgnoreDuplicateKey(boolean ignoreDuplicateKey) {
this.ignoreDuplicateKey = ignoreDuplicateKey;
return this;
}
}

View File

@@ -392,7 +392,9 @@ public class JSONObject extends MapWrapper<String, Object> implements JSON, JSON
// 忽略值模式下如果值为空清除key
this.remove(key);
} else {
if (checkDuplicate && containsKey(key)) {
/*如果允许多个key就不抛出异常使用后面的值覆盖前面的值*/
boolean ignoreDuplicateKey = this.config.isIgnoreDuplicateKey();
if (checkDuplicate && containsKey(key) && false == ignoreDuplicateKey) {
throw new JSONException("Duplicate key \"{}\"", key);
}