diff --git a/hutool-json/src/main/java/cn/hutool/json/JSONConfig.java b/hutool-json/src/main/java/cn/hutool/json/JSONConfig.java index 0b437a8f3..95b1039bf 100755 --- a/hutool-json/src/main/java/cn/hutool/json/JSONConfig.java +++ b/hutool-json/src/main/java/cn/hutool/json/JSONConfig.java @@ -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; + } } diff --git a/hutool-json/src/main/java/cn/hutool/json/JSONObject.java b/hutool-json/src/main/java/cn/hutool/json/JSONObject.java index 921d19df8..1704c8daa 100755 --- a/hutool-json/src/main/java/cn/hutool/json/JSONObject.java +++ b/hutool-json/src/main/java/cn/hutool/json/JSONObject.java @@ -392,7 +392,9 @@ public class JSONObject extends MapWrapper 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); } diff --git a/hutool-json/src/test/java/cn/hutool/json/JSONUtilTest.java b/hutool-json/src/test/java/cn/hutool/json/JSONUtilTest.java index 3be9a3fbb..5f2e8bb41 100644 --- a/hutool-json/src/test/java/cn/hutool/json/JSONUtilTest.java +++ b/hutool-json/src/test/java/cn/hutool/json/JSONUtilTest.java @@ -234,4 +234,14 @@ public class JSONUtilTest { final String xmlStr = JSONUtil.toXmlStr(obj); Assert.assertEquals("v1abc", xmlStr); } + + @Test + public void testDuplicateKey(){ + String str = "{id:123, name:\"张三\", name:\"李四\"}"; + + JSONObject jsonObject = JSONUtil.parseObj(str, JSONConfig.create().setIgnoreDuplicateKey(true)); + System.out.println(jsonObject.toString()); + + Assert.assertNotNull(jsonObject); + } }