mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-05-09 23:51:34 +08:00
json序列化时,增加允许多个相同的key配置
This commit is contained in:
parent
0ca9627663
commit
4eb720bb31
@ -44,6 +44,11 @@ public class JSONConfig implements Serializable {
|
|||||||
*/
|
*/
|
||||||
private boolean stripTrailingZeros = true;
|
private boolean stripTrailingZeros = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否忽略多个相同的key
|
||||||
|
*/
|
||||||
|
private boolean ignoreDuplicateKey = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建默认的配置项
|
* 创建默认的配置项
|
||||||
*
|
*
|
||||||
@ -235,4 +240,22 @@ public class JSONConfig implements Serializable {
|
|||||||
this.stripTrailingZeros = stripTrailingZeros;
|
this.stripTrailingZeros = stripTrailingZeros;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否忽略多个相同的key
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public boolean isIgnoreDuplicateKey() {
|
||||||
|
return ignoreDuplicateKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否忽略多个相同的key
|
||||||
|
* @param ignoreDuplicateKey
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public JSONConfig setIgnoreDuplicateKey(boolean ignoreDuplicateKey) {
|
||||||
|
this.ignoreDuplicateKey = ignoreDuplicateKey;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -392,7 +392,9 @@ public class JSONObject extends MapWrapper<String, Object> implements JSON, JSON
|
|||||||
// 忽略值模式下如果值为空清除key
|
// 忽略值模式下如果值为空清除key
|
||||||
this.remove(key);
|
this.remove(key);
|
||||||
} else {
|
} else {
|
||||||
if (checkDuplicate && containsKey(key)) {
|
/*如果允许多个key,就不抛出异常,使用后面的值覆盖前面的值*/
|
||||||
|
boolean ignoreDuplicateKey = this.config.isIgnoreDuplicateKey();
|
||||||
|
if (checkDuplicate && containsKey(key) && false == ignoreDuplicateKey) {
|
||||||
throw new JSONException("Duplicate key \"{}\"", key);
|
throw new JSONException("Duplicate key \"{}\"", key);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -234,4 +234,14 @@ public class JSONUtilTest {
|
|||||||
final String xmlStr = JSONUtil.toXmlStr(obj);
|
final String xmlStr = JSONUtil.toXmlStr(obj);
|
||||||
Assert.assertEquals("<key1>v1</key1><key2>a</key2><key2>b</key2><key2>c</key2>", xmlStr);
|
Assert.assertEquals("<key1>v1</key1><key2>a</key2><key2>b</key2><key2>c</key2>", 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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user