add DuplicateMode

This commit is contained in:
Looly 2024-10-01 23:44:00 +08:00
parent 449fe1fa2e
commit e54c0b26f6
34 changed files with 217 additions and 179 deletions

View File

@ -32,7 +32,7 @@ public class IssueIAFKWPTest {
@Test
void urlWithFormTest() {
final JSONObject obj = JSONUtil.ofObj();
obj.putObj("fields", ListUtil.of("1", "2", "good"));
obj.putValue("fields", ListUtil.of("1", "2", "good"));
final Map<String, Object> params = new HashMap<>();
params.put("query", obj.toString());

View File

@ -38,8 +38,8 @@ public class RestTest {
final Request request = Request.of("http://localhost:8090/rest/restTest/")
.method(Method.POST)
.body(JSONUtil.ofObj()
.putObj("aaa", "aaaValue")
.putObj("键2", "值2").toString());
.putValue("aaa", "aaaValue")
.putValue("键2", "值2").toString());
Assertions.assertEquals("application/json;charset=UTF-8", request.header(HeaderName.CONTENT_TYPE));
}
@ -50,8 +50,8 @@ public class RestTest {
final Request request = Request.of("http://localhost:8090/rest/restTest/")
.method(Method.POST)
.body(JSONUtil.ofObj()
.putObj("aaa", "aaaValue")
.putObj("键2", "值2").toString());
.putValue("aaa", "aaaValue")
.putValue("键2", "值2").toString());
Console.log(request.send().body());
}
@ -59,8 +59,8 @@ public class RestTest {
@Disabled
public void postTest2() {
final String result = HttpUtil.post("http://localhost:8090/rest/restTest/", JSONUtil.ofObj()//
.putObj("aaa", "aaaValue")
.putObj("键2", "值2").toString());
.putValue("aaa", "aaaValue")
.putValue("键2", "值2").toString());
Console.log(result);
}
@ -70,8 +70,8 @@ public class RestTest {
final Request request = Request.of("http://localhost:8888/restTest")//
.header(HeaderName.CONTENT_TYPE, "application/json")
.body(JSONUtil.ofObj()
.putObj("aaa", "aaaValue")
.putObj("键2", "值2").toString());
.putValue("aaa", "aaaValue")
.putValue("键2", "值2").toString());
//noinspection resource
Console.log(request.send().body());
}

View File

@ -44,9 +44,9 @@ public class SimpleServerTest {
// 返回JSON数据测试
.addAction("/restTest", (request, response) -> {
final String res = JSONUtil.ofObj()
.putObj("id", 1)
.putObj("method", request.getMethod())
.putObj("request", request.getBody())
.putValue("id", 1)
.putValue("method", request.getMethod())
.putValue("request", request.getBody())
.toStringPretty();
response.write(res, ContentType.JSON.toString());
})

View File

@ -119,7 +119,7 @@ public class JSONArray extends ListWrapper<JSON> implements JSON, JSONGetter<Int
* @param value 可以是 Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the JSONNull.NULL
* @return this.
*/
public JSONArray addObj(final Object value) {
public JSONArray addValue(final Object value) {
// add时如果value为字符串不解析而是作为JSONPrimitive对待
this.add(this.factory.getMapper().toJSON(value, false));
return this;
@ -138,7 +138,7 @@ public class JSONArray extends ListWrapper<JSON> implements JSON, JSONGetter<Int
}
final JSONObject jo = this.factory.ofObj();
for (int i = 0; i < names.size(); i += 1) {
jo.putObj(names.getStr(i), this.getObj(i));
jo.putValue(names.getStr(i), this.getObj(i));
}
return jo;
}
@ -171,7 +171,7 @@ public class JSONArray extends ListWrapper<JSON> implements JSON, JSONGetter<Int
* @param element 值对象. 可以是以下类型: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull.NULL.
* @return this
*/
public JSONArray setObj(final int index, final Object element) {
public JSONArray setValue(final int index, final Object element) {
// set时如果value为字符串不解析而是作为JSONPrimitive对待
set(index, this.factory.getMapper().toJSON(element, false));
return this;

View File

@ -65,9 +65,9 @@ public class JSONConfig implements Serializable {
*/
private boolean stripTrailingZeros = true;
/**
* 是否检查重复key
* 重复key的put策略
*/
private boolean checkDuplicate;
private DuplicateMode duplicateMode = DuplicateMode.OVERRIDE;
/**
* Number写出模式
*/
@ -247,24 +247,22 @@ public class JSONConfig implements Serializable {
}
/**
* 是否检查多个相同的key
* 获取key重复策略
*
* @return 是否检查多个相同的key
* @since 5.8.5
* @return key重复策略
*/
public boolean isCheckDuplicate() {
return checkDuplicate;
public DuplicateMode getDuplicateMode() {
return duplicateMode;
}
/**
* 是否检查多个相同的key
* 设置key重复策略
*
* @param checkDuplicate 是否检查多个相同的key
* @param duplicateMode key重复策略
* @return this
* @since 5.8.5
*/
public JSONConfig setCheckDuplicate(final boolean checkDuplicate) {
this.checkDuplicate = checkDuplicate;
public JSONConfig set(final DuplicateMode duplicateMode) {
this.duplicateMode = duplicateMode;
return this;
}
@ -290,4 +288,23 @@ public class JSONConfig implements Serializable {
this.numberWriteMode = numberWriteMode;
return this;
}
/**
* 重复key或重复对象处理方式<br>
* 只针对{@link JSONObject}检查在put时key的重复情况
*/
public enum DuplicateMode {
/**
* 抛出异常
*/
THROW,
/**
* 覆盖
*/
OVERRIDE,
/**
* 忽略
*/
IGNORE
}
}

View File

@ -204,10 +204,13 @@ public class JSONFactory {
/**
* 创建JSONPrimitive
*
* @param value
* @param value {@code null}则返回{@code null}
* @return JSONPrimitive
*/
public JSONPrimitive ofPrimitive(final Object value) {
if(null == value){
return null;
}
return new JSONPrimitive(value, this);
}

View File

@ -144,7 +144,7 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGe
}
// endregion
// region ----- put
// region ----- increment or append
/**
* 对值加一如果值不存在赋值1如果为数字类型做加一操作
*
@ -155,7 +155,7 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGe
public JSONObject increment(final String key) throws JSONException {
final JSON json = this.get(key);
if(null == json){
return putObj(key, 1);
return putValue(key, 1);
}
if(json instanceof JSONPrimitive){
@ -186,15 +186,17 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGe
public JSONObject append(final String key, final Object value) throws JSONException {
final Object object = this.getObj(key);
if (object == null) {
this.putObj(key, value);
this.putValue(key, value);
} else if (object instanceof JSONArray) {
((JSONArray) object).addObj(value);
((JSONArray) object).addValue(value);
} else {
this.putObj(key, factory.ofArray().addObj(object).addObj(value));
this.putValue(key, factory.ofArray().addValue(object).addValue(value));
}
return this;
}
// endregion
// region ----- put
/**
* 通过lambda批量设置值<br>
* 实际使用时可以使用getXXX的方法引用来完成键值对的赋值
@ -207,7 +209,7 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGe
* @return this
*/
public JSONObject putFields(final SerSupplier<?>... fields) {
Arrays.stream(fields).forEach(f -> putObj(LambdaUtil.getFieldName(f), f.get()));
Arrays.stream(fields).forEach(f -> putValue(LambdaUtil.getFieldName(f), f.get()));
return this;
}
@ -218,9 +220,9 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGe
* @return this.
* @throws JSONException 值是无穷数字抛出此异常
*/
public JSONObject putAllObj(final Map<?, ?> map) {
public JSONObject putAllValue(final Map<?, ?> map) {
if(MapUtil.isNotEmpty(map)){
map.forEach((key, value) -> putObj(StrUtil.toStringOrNull(key), value));
map.forEach((key, value) -> putValue(StrUtil.toStringOrNull(key), value));
}
return this;
}
@ -229,11 +231,11 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGe
* 设置键值对到JSONObject中在忽略null模式下如果值为{@code null}将此键移除
*
* @param key
* @param value 值对象. 可以是以下类型: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull.NULL.
* @param value 值对象. 可以是以下类型: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the {@code null}
* @return this.
* @throws JSONException 值是无穷数字抛出此异常
*/
public JSONObject putObj(final String key, final Object value) throws JSONException {
public JSONObject putValue(final String key, final Object value) throws JSONException {
// put时如果value为字符串不解析而是作为JSONPrimitive对待
this.put(key, factory.getMapper().toJSON(value, false));
return this;
@ -253,11 +255,17 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGe
return null;
}
final boolean ignoreNullValue = config().isIgnoreNullValue();
if (null == value && ignoreNullValue) {
final JSONConfig config = config();
if (null == value && config.isIgnoreNullValue()) {
// 忽略值模式下如果值为空清除key
return this.remove(key);
} else if (config().isCheckDuplicate() && containsKey(key)) {
}
final JSONConfig.DuplicateMode duplicateMode = config.getDuplicateMode();
if (JSONConfig.DuplicateMode.OVERRIDE != duplicateMode && containsKey(key)) {
if(JSONConfig.DuplicateMode.IGNORE == duplicateMode){
return null;
}
throw new JSONException("Duplicate key \"{}\"", key);
}
return super.put(key, value);

View File

@ -55,7 +55,7 @@ public class Claims implements Serializable {
claimJSON.remove(name);
return;
}
claimJSON.putObj(name, value);
claimJSON.putValue(name, value);
}
/**

View File

@ -202,7 +202,7 @@ public class JSONParser {
final MutableEntry<Object, Object> entry = new MutableEntry<>(key, value);
if (predicate.test(entry)) {
// 使用修改后的键值对
jsonObject.putObj((String) entry.getKey(), entry.getValue());
jsonObject.putValue((String) entry.getKey(), entry.getValue());
}
} else {
jsonObject.put(key, value);
@ -242,7 +242,7 @@ public class JSONParser {
final MutableEntry<Object, Object> entry = MutableEntry.of(jsonArray.size(), value);
if (predicate.test(entry)) {
// 使用修改后的键值对用户修改后可能不是JSON此处使用set调用mapper转换
jsonArray.setObj((Integer) entry.getKey(), entry.getValue());
jsonArray.setValue((Integer) entry.getKey(), entry.getValue());
}
} else {
jsonArray.add(value);

View File

@ -109,7 +109,7 @@ public class ArrayTypeAdapter implements MatcherJSONSerializer<Object>, MatcherJ
// 非标准的二进制流则按照普通数组对待
final JSONArray result = context.getOrCreateArray();
for (final byte b : bytes) {
result.addObj(b);
result.addValue(b);
}
return result;
}

View File

@ -59,7 +59,7 @@ public class EntryTypeAdapter implements MatcherJSONSerializer<Map.Entry<?, ?>>,
@Override
public JSON serialize(final Map.Entry<?, ?> bean, final JSONContext context) {
return context.getOrCreateObj()
.putObj(ConvertUtil.toStr(bean.getKey()), bean.getValue());
.putValue(ConvertUtil.toStr(bean.getKey()), bean.getValue());
}
@Override

View File

@ -114,7 +114,7 @@ public class IterTypeAdapter implements MatcherJSONSerializer<Object>, MatcherJS
next = iter.next();
// 检查循环引用
if (next != source) {
jsonArray.addObj(next);
jsonArray.addValue(next);
}
}
}

View File

@ -82,7 +82,7 @@ public class MapTypeAdapter implements MatcherJSONSerializer<Map<?, ?>>, Matcher
final JSONObject result = context.getOrCreateObj();
// 注入键值对
for (final Map.Entry<?, ?> e : bean.entrySet()) {
result.putObj(StrUtil.toStringOrNull(e.getKey()), e.getValue());
result.putValue(StrUtil.toStringOrNull(e.getKey()), e.getValue());
}
return result;
}

View File

@ -87,10 +87,10 @@ public class ResourceBundleSerializer implements MatcherJSONSerializer<ResourceB
JSONObject nextTarget = target.getJSONObject(segment);
if (nextTarget == null) {
nextTarget = JSONUtil.ofObj(target.config());
target.putObj(segment, nextTarget);
target.putValue(segment, nextTarget);
}
target = nextTarget;
}
target.putObj(path[last], value);
target.putValue(path[last], value);
}
}

View File

@ -136,24 +136,24 @@ public class TemporalTypeAdapter implements MatcherJSONSerializer<TemporalAccess
private static void toJSONObject(final TemporalAccessor bean, final JSONObject json) {
if (bean instanceof LocalDate) {
final LocalDate localDate = (LocalDate) bean;
json.putObj(YEAR_KEY, localDate.getYear());
json.putObj(MONTH_KEY, localDate.getMonthValue());
json.putObj(DAY_KEY, localDate.getDayOfMonth());
json.putValue(YEAR_KEY, localDate.getYear());
json.putValue(MONTH_KEY, localDate.getMonthValue());
json.putValue(DAY_KEY, localDate.getDayOfMonth());
} else if (bean instanceof LocalDateTime) {
final LocalDateTime localDateTime = (LocalDateTime) bean;
json.putObj(YEAR_KEY, localDateTime.getYear());
json.putObj(MONTH_KEY, localDateTime.getMonthValue());
json.putObj(DAY_KEY, localDateTime.getDayOfMonth());
json.putObj(HOUR_KEY, localDateTime.getHour());
json.putObj(MINUTE_KEY, localDateTime.getMinute());
json.putObj(SECOND_KEY, localDateTime.getSecond());
json.putObj(NANO_KEY, localDateTime.getNano());
json.putValue(YEAR_KEY, localDateTime.getYear());
json.putValue(MONTH_KEY, localDateTime.getMonthValue());
json.putValue(DAY_KEY, localDateTime.getDayOfMonth());
json.putValue(HOUR_KEY, localDateTime.getHour());
json.putValue(MINUTE_KEY, localDateTime.getMinute());
json.putValue(SECOND_KEY, localDateTime.getSecond());
json.putValue(NANO_KEY, localDateTime.getNano());
} else if (bean instanceof LocalTime) {
final LocalTime localTime = (LocalTime) bean;
json.putObj(HOUR_KEY, localTime.getHour());
json.putObj(MINUTE_KEY, localTime.getMinute());
json.putObj(SECOND_KEY, localTime.getSecond());
json.putObj(NANO_KEY, localTime.getNano());
json.putValue(HOUR_KEY, localTime.getHour());
json.putValue(MINUTE_KEY, localTime.getMinute());
json.putValue(SECOND_KEY, localTime.getSecond());
json.putValue(NANO_KEY, localTime.getNano());
} else{
throw new JSONException("Unsupported type: {}", bean.getClass().getName());
}

View File

@ -84,10 +84,10 @@ public class BeanToJSONCopier implements Copier<JSONObject> {
final MutableEntry<Object, Object> entry = new MutableEntry<>(fieldName, sValue);
if (predicate.test(entry)) {
// 使用修改后的键值对
target.putObj((String) entry.getKey(), entry.getValue());
target.putValue((String) entry.getKey(), entry.getValue());
}
} else if (null != sValue || !ignoreNullValue) {
target.putObj(fieldName, sValue);
target.putValue(fieldName, sValue);
}
}
}

View File

@ -82,9 +82,9 @@ public class JSONNodeBeanFactory implements NodeBeanFactory<JSON> {
return bean;
} else if (node instanceof NameNode) {
if(bean instanceof JSONObject){
((JSONObject) bean).putObj(((NameNode) node).getName(), value);
((JSONObject) bean).putValue(((NameNode) node).getName(), value);
} else if(bean instanceof JSONArray){
((JSONArray) bean).setObj(Integer.parseInt(((NameNode) node).getName()), value);
((JSONArray) bean).setValue(Integer.parseInt(((NameNode) node).getName()), value);
}
return bean;
}

View File

@ -51,7 +51,7 @@ public class JSONArrayTest {
JSONArray jsonArray = JSONUtil.parseArray(jsonObject);
assertEquals(new JSONArray(), jsonArray);
jsonObject.putObj("key1", "value1");
jsonObject.putValue("key1", "value1");
jsonArray = JSONUtil.parseArray(jsonObject, JSONConfig.of());
assertEquals(1, jsonArray.size());
assertEquals("[{\"key1\":\"value1\"}]", jsonArray.toString());
@ -70,9 +70,9 @@ public class JSONArrayTest {
final JSONArray array = JSONUtil.ofArray();
// 方法2
// JSONArray array = new JSONArray();
array.addObj("value1");
array.addObj("value2");
array.addObj("value3");
array.addValue("value1");
array.addValue("value2");
array.addValue("value3");
assertEquals(array.getObj(0), "value1");
}
@ -240,12 +240,12 @@ public class JSONArrayTest {
@Test
public void putToIndexTest() {
JSONArray jsonArray = new JSONArray();
jsonArray.setObj(3, "test");
jsonArray.setValue(3, "test");
// 默认忽略null值因此空位无值只有一个值
assertEquals(1, jsonArray.size());
jsonArray = new JSONArray(JSONConfig.of().setIgnoreNullValue(false));
jsonArray.setObj(2, "test");
jsonArray.setValue(2, "test");
// 第三个位置插入值0~2都是null
assertEquals(3, jsonArray.size());
}
@ -254,7 +254,7 @@ public class JSONArrayTest {
@Test
public void putTest2() {
final JSONArray jsonArray = new JSONArray();
jsonArray.setObj(0, 1);
jsonArray.setValue(0, 1);
assertEquals(1, jsonArray.size());
assertEquals(1, jsonArray.getObj(0));
}
@ -276,10 +276,10 @@ public class JSONArrayTest {
@Test
public void filterIncludeTest() {
final JSONArray json1 = JSONUtil.ofArray()
.addObj("value1")
.addObj("value2")
.addObj("value3")
.addObj(true);
.addValue("value1")
.addValue("value2")
.addValue("value3")
.addValue(true);
final String s = json1.toJSONString(0, (pair) -> ((JSONPrimitive)pair.getValue()).getValue().equals("value2"));
assertEquals("[\"value2\"]", s);
@ -288,10 +288,10 @@ public class JSONArrayTest {
@Test
public void filterExcludeTest() {
final JSONArray json1 = JSONUtil.ofArray()
.addObj("value1")
.addObj("value2")
.addObj("value3")
.addObj(true);
.addValue("value1")
.addValue("value2")
.addValue("value3")
.addValue(true);
final String s = json1.toJSONString(0, (pair) -> !((JSONPrimitive)pair.getValue()).getValue().equals("value2"));
assertEquals("[\"value1\",\"value3\",true]", s);
@ -300,7 +300,7 @@ public class JSONArrayTest {
@Test
public void putNullTest() {
final JSONArray array = JSONUtil.ofArray(JSONConfig.of().setIgnoreNullValue(false));
array.addObj(null);
array.addValue(null);
assertEquals("[null]", array.toString());
}
@ -322,7 +322,7 @@ public class JSONArrayTest {
if(mutable.getKey() instanceof Integer){
final JSONObject o = (JSONObject) mutable.getValue();
if ("111".equals(o.getStr("id"))) {
o.putObj("name", "test1_edit");
o.putValue("name", "test1_edit");
}
}
return true;
@ -335,9 +335,9 @@ public class JSONArrayTest {
@Test
void jsonIterTest() {
final JSONArray array = JSONUtil.ofArray();
array.add(JSONUtil.ofObj().putObj("name", "aaa"));
array.add(JSONUtil.ofObj().putObj("name", "bbb"));
array.add(JSONUtil.ofObj().putObj("name", "ccc"));
array.add(JSONUtil.ofObj().putValue("name", "aaa"));
array.add(JSONUtil.ofObj().putValue("name", "bbb"));
array.add(JSONUtil.ofObj().putValue("name", "ccc"));
final StringBuilder result = new StringBuilder();
array.forEach(result::append);

View File

@ -51,22 +51,22 @@ public class JSONNullTest {
@Test
public void setNullTest(){
// 忽略null
String json1 = JSONUtil.ofObj().putObj("key1", null).toString();
String json1 = JSONUtil.ofObj().putValue("key1", null).toString();
Assertions.assertEquals("{}", json1);
// 不忽略null
json1 = JSONUtil.ofObj(JSONConfig.of().setIgnoreNullValue(false)).putObj("key1", null).toString();
json1 = JSONUtil.ofObj(JSONConfig.of().setIgnoreNullValue(false)).putValue("key1", null).toString();
Assertions.assertEquals("{\"key1\":null}", json1);
}
@Test
public void setNullOfJSONArrayTest(){
// 忽略null
String json1 = JSONUtil.ofArray().addObj(null).toString();
String json1 = JSONUtil.ofArray().addValue(null).toString();
Assertions.assertEquals("[]", json1);
// 不忽略null
json1 = JSONUtil.ofArray(JSONConfig.of().setIgnoreNullValue(false)).addObj(null).toString();
json1 = JSONUtil.ofArray(JSONConfig.of().setIgnoreNullValue(false)).addValue(null).toString();
Assertions.assertEquals("[null]", json1);
}
}

View File

@ -75,18 +75,18 @@ public class JSONObjectTest {
@Test
public void toStringTest3() {
final JSONObject json = JSONUtil.ofObj(JSONConfig.of().setDateFormat(DatePattern.NORM_DATE_PATTERN))//
.putObj("dateTime", DateUtil.parse("2019-05-02 22:12:01"));
.putValue("dateTime", DateUtil.parse("2019-05-02 22:12:01"));
assertEquals("{\"dateTime\":\"2019-05-02\"}", json.toString());
}
@Test
public void toStringWithDateTest() {
JSONObject json = JSONUtil.ofObj().putObj("date", DateUtil.parse("2019-05-08 19:18:21"));
JSONObject json = JSONUtil.ofObj().putValue("date", DateUtil.parse("2019-05-08 19:18:21"));
assert json != null;
assertEquals("{\"date\":1557314301000}", json.toString());
json = JSONUtil.ofObj(JSONConfig.of().setDateFormat(DatePattern.NORM_DATE_PATTERN))
.putObj("date", DateUtil.parse("2019-05-08 19:18:21"));
.putValue("date", DateUtil.parse("2019-05-08 19:18:21"));
assertEquals("{\"date\":\"2019-05-08\"}", json.toString());
}
@ -94,14 +94,14 @@ public class JSONObjectTest {
@Test
public void putAllTest() {
final JSONObject json1 = JSONUtil.ofObj()
.putObj("a", "value1")
.putObj("b", "value2")
.putObj("c", "value3")
.putObj("d", true);
.putValue("a", "value1")
.putValue("b", "value2")
.putValue("c", "value3")
.putValue("d", true);
final JSONObject json2 = JSONUtil.ofObj()
.putObj("a", "value21")
.putObj("b", "value22");
.putValue("a", "value21")
.putValue("b", "value22");
// putAll操作会覆盖相同key的值因此a,b两个key的值改变c的值不变
json1.putAll(json2);
@ -193,12 +193,12 @@ public class JSONObjectTest {
@Test
public void toBeanTest() {
final JSONObject subJson = JSONUtil.ofObj().putObj("value1", "strValue1").putObj("value2", "234");
final JSONObject json = JSONUtil.ofObj(JSONConfig.of().setIgnoreError(true)).putObj("strValue", "strTest").putObj("intValue", 123)
final JSONObject subJson = JSONUtil.ofObj().putValue("value1", "strValue1").putValue("value2", "234");
final JSONObject json = JSONUtil.ofObj(JSONConfig.of().setIgnoreError(true)).putValue("strValue", "strTest").putValue("intValue", 123)
// 测试空字符串转对象
.putObj("doubleValue", "")
.putObj("beanValue", subJson)
.putObj("list", JSONUtil.ofArray().addObj("a").addObj("b")).putObj("testEnum", "TYPE_A");
.putValue("doubleValue", "")
.putValue("beanValue", subJson)
.putValue("list", JSONUtil.ofArray().addValue("a").addValue("b")).putValue("testEnum", "TYPE_A");
final TestBean bean = json.toBean(TestBean.class);
assertEquals("a", bean.getList().get(0));
@ -214,11 +214,11 @@ public class JSONObjectTest {
@Test
public void toBeanNullStrTest() {
final JSONObject json = JSONUtil.ofObj(JSONConfig.of().setIgnoreError(true))//
.putObj("strValue", "null")//
.putObj("intValue", 123)//
.putValue("strValue", "null")//
.putValue("intValue", 123)//
// 子对象对应"null"字符串如果忽略错误跳过否则抛出转换异常
.putObj("beanValue", "null")//
.putObj("list", JSONUtil.ofArray().addObj("a").addObj("b"));
.putValue("beanValue", "null")//
.putValue("list", JSONUtil.ofArray().addValue("a").addValue("b"));
final TestBean bean = json.toBean(TestBean.class);
// 当JSON中为字符串"null"时应被当作字符串处理
@ -230,7 +230,7 @@ public class JSONObjectTest {
@Test
void addListTest(){
final JSONObject json = JSONUtil.ofObj();
json.putObj("list", ListUtil.of(1, 2, 3));
json.putValue("list", ListUtil.of(1, 2, 3));
Assertions.assertEquals("{\"list\":[1,2,3]}", json.toString());
}
@ -288,11 +288,11 @@ public class JSONObjectTest {
@Test
public void toBeanTest6() {
final JSONObject json = JSONUtil.ofObj()
.putObj("targetUrl", "http://test.com")
.putObj("success", "true")
.putObj("result", JSONUtil.ofObj()
.putObj("token", "tokenTest")
.putObj("userId", "测试用户1"));
.putValue("targetUrl", "http://test.com")
.putValue("success", "true")
.putValue("result", JSONUtil.ofObj()
.putValue("token", "tokenTest")
.putValue("userId", "测试用户1"));
final TokenAuthWarp2 bean = json.toBean(TokenAuthWarp2.class);
assertEquals("http://test.com", bean.getTargetUrl());
@ -353,8 +353,8 @@ public class JSONObjectTest {
@Test
public void parseBeanTest3() {
final JSONObject json = JSONUtil.ofObj()
.putObj("code", 22)
.putObj("data", "{\"jobId\": \"abc\", \"videoUrl\": \"http://a.com/a.mp4\"}");
.putValue("code", 22)
.putValue("data", "{\"jobId\": \"abc\", \"videoUrl\": \"http://a.com/a.mp4\"}");
final JSONBean bean = json.toBean(JSONBean.class);
assertEquals(22, bean.getCode());
@ -393,9 +393,9 @@ public class JSONObjectTest {
@Test
public void beanTransTest3() {
final JSONObject userAJson = JSONUtil.ofObj()
.putObj("a", "AValue")
.putObj("name", "nameValue")
.putObj("date", "08:00:00");
.putValue("a", "AValue")
.putValue("name", "nameValue")
.putValue("date", "08:00:00");
final UserA bean = JSONUtil.toBean(userAJson.toString(), UserA.class);
assertEquals(DateUtil.formatToday() + " 08:00:00", DateUtil.date(bean.getDate()).toString());
}
@ -449,8 +449,8 @@ public class JSONObjectTest {
assertEquals(Integer.valueOf(35), jsonObject.getInt("age"));
final JSONObject json = JSONUtil.ofObj()
.putObj("name", "张三")
.putObj("age", 35);
.putValue("name", "张三")
.putValue("age", 35);
final BeanWithAlias bean = JSONUtil.toBean(Objects.requireNonNull(json).toString(), BeanWithAlias.class);
assertEquals("张三", bean.getValue1());
assertEquals(Integer.valueOf(35), bean.getValue2());
@ -475,9 +475,9 @@ public class JSONObjectTest {
final Date date = DateUtil.parse("2020-06-05 11:16:11");
final JSONObject json = new JSONObject(jsonConfig);
json.putObj("date", date);
json.putObj("bbb", "222");
json.putObj("aaa", "123");
json.putValue("date", date);
json.putValue("bbb", "222");
json.putValue("aaa", "123");
final String jsonStr = "{\"date\":\"2020#06#05\",\"bbb\":\"222\",\"aaa\":\"123\"}";
@ -495,7 +495,7 @@ public class JSONObjectTest {
final Date date = DateUtil.parse("2020-06-05 11:16:11");
final JSONObject json = new JSONObject(jsonConfig);
json.putObj("date", date);
json.putValue("date", date);
assertEquals("{\"date\":1591326971}", json.toString());
@ -511,9 +511,9 @@ public class JSONObjectTest {
final Date date = DateUtil.parse("2020-06-05 11:16:11");
final JSONObject json = new JSONObject(jsonConfig);
json.putObj("date", date);
json.putObj("bbb", "222");
json.putObj("aaa", "123");
json.putValue("date", date);
json.putValue("bbb", "222");
json.putValue("aaa", "123");
final String jsonStr = "{\"date\":1591326971,\"bbb\":\"222\",\"aaa\":\"123\"}";
@ -527,7 +527,7 @@ public class JSONObjectTest {
@Test
public void getTimestampTest() {
final String timeStr = "1970-01-01 00:00:00";
final JSONObject jsonObject = JSONUtil.ofObj().putObj("time", timeStr);
final JSONObject jsonObject = JSONUtil.ofObj().putValue("time", timeStr);
final Timestamp time = jsonObject.get("time", Timestamp.class);
assertEquals("1970-01-01 00:00:00.0", time.toString());
}
@ -670,10 +670,10 @@ public class JSONObjectTest {
@Test
public void filterIncludeTest() {
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
.putObj("a", "value1")
.putObj("b", "value2")
.putObj("c", "value3")
.putObj("d", true);
.putValue("a", "value1")
.putValue("b", "value2")
.putValue("c", "value3")
.putValue("d", true);
final String s = json1.toJSONString(0, (pair) -> pair.getKey().equals("b"));
assertEquals("{\"b\":\"value2\"}", s);
@ -682,10 +682,10 @@ public class JSONObjectTest {
@Test
public void filterExcludeTest() {
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
.putObj("a", "value1")
.putObj("b", "value2")
.putObj("c", "value3")
.putObj("d", true);
.putValue("a", "value1")
.putValue("b", "value2")
.putValue("c", "value3")
.putValue("d", true);
final String s = json1.toJSONString(0, (pair) -> !pair.getKey().equals("b"));
assertEquals("{\"a\":\"value1\",\"c\":\"value3\",\"d\":true}", s);
@ -694,10 +694,10 @@ public class JSONObjectTest {
@Test
public void editTest() {
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
.putObj("a", "value1")
.putObj("b", "value2")
.putObj("c", "value3")
.putObj("d", true);
.putValue("a", "value1")
.putValue("b", "value2")
.putValue("c", "value3")
.putValue("d", true);
final String s = json1.toJSONString(0, (pair) -> {
if ("b".equals(pair.getKey())) {
@ -715,10 +715,10 @@ public class JSONObjectTest {
@Test
public void toUnderLineCaseTest() {
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
.putObj("aKey", "value1")
.putObj("bJob", "value2")
.putObj("cGood", "value3")
.putObj("d", true);
.putValue("aKey", "value1")
.putValue("bJob", "value2")
.putValue("cGood", "value3")
.putValue("d", true);
final String s = json1.toJSONString(0, (pair) -> {
pair.setKey(StrUtil.toUnderlineCase((String)pair.getKey()));
@ -730,8 +730,8 @@ public class JSONObjectTest {
@Test
public void nullToEmptyTest() {
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of().setIgnoreNullValue(false))
.putObj("a", null)
.putObj("b", "value2");
.putValue("a", null)
.putValue("b", "value2");
final String s = json1.toJSONString(0, (pair) -> {
pair.setValue(ObjUtil.defaultIfNull(pair.getValue(), StrUtil.EMPTY));

View File

@ -186,9 +186,9 @@ public class JSONUtilTest {
public void toJsonStrTest3() {
// 验证某个字段为JSON字符串时转义是否规范
final JSONObject object = new JSONObject(JSONConfig.of().setIgnoreError(true));
object.putObj("name", "123123");
object.putObj("value", "\\");
object.putObj("value2", "</");
object.putValue("name", "123123");
object.putValue("value", "\\");
object.putValue("value2", "</");
final HashMap<String, String> map = MapUtil.newHashMap();
map.put("user", object.toString());
@ -277,12 +277,12 @@ public class JSONUtilTest {
public void setStripTrailingZerosTest() {
// 默认去除多余的0
final JSONObject jsonObjectDefault = JSONUtil.ofObj()
.putObj("test2", 12.00D);
.putValue("test2", 12.00D);
assertEquals("{\"test2\":12}", jsonObjectDefault.toString());
// 不去除多余的0
final JSONObject jsonObject = JSONUtil.ofObj(JSONConfig.of().setStripTrailingZeros(false))
.putObj("test2", 12.00D);
.putValue("test2", 12.00D);
assertEquals("{\"test2\":12.0}", jsonObject.toString());
// 去除多余的0
@ -304,7 +304,7 @@ public class JSONUtilTest {
public void sqlExceptionTest() {
//https://github.com/dromara/hutool/issues/1399
// SQLException实现了Iterable接口默认是遍历之会栈溢出修正后只返回string
final JSONObject set = JSONUtil.ofObj().putObj("test", new SQLException("test"));
final JSONObject set = JSONUtil.ofObj().putValue("test", new SQLException("test"));
assertEquals("{\"test\":\"java.sql.SQLException: test\"}", set.toString());
}
@ -318,8 +318,8 @@ public class JSONUtilTest {
@Test
public void toXmlTest() {
final JSONObject obj = JSONUtil.ofObj();
obj.putObj("key1", "v1")
.putObj("key2", ListUtil.view("a", "b", "c"));
obj.putValue("key1", "v1")
.putValue("key2", ListUtil.view("a", "b", "c"));
final String xmlStr = JSONUtil.toXmlStr(obj);
assertEquals("<key1>v1</key1><key2>a</key2><key2>b</key2><key2>c</key2>", xmlStr);
}

View File

@ -27,7 +27,7 @@ public class JSONWriterTest {
@Test
public void writeDateTest() {
final JSONObject jsonObject = JSONUtil.ofObj(JSONConfig.of().setDateFormat("yyyy-MM-dd"))
.putObj("date", DateUtil.parse("2022-09-30"));
.putValue("date", DateUtil.parse("2022-09-30"));
// 日期原样写入
final Date date = jsonObject.getDate("date");

View File

@ -31,7 +31,7 @@ import java.sql.SQLException;
public class Issue1399Test {
@Test
void sqlExceptionTest() {
final JSONObject set = JSONUtil.ofObj().putObj("error", new SQLException("test"));
final JSONObject set = JSONUtil.ofObj().putValue("error", new SQLException("test"));
final String jsonStr = set.toString();
Assertions.assertEquals("{\"error\":\"java.sql.SQLException: test\"}", jsonStr);

View File

@ -75,7 +75,7 @@ public class Issue2090Test {
@Test
public void monthTest(){
final JSONObject jsonObject = new JSONObject();
jsonObject.putObj("month", Month.JANUARY);
jsonObject.putValue("month", Month.JANUARY);
Assertions.assertEquals("{\"month\":1}", jsonObject.toString());
final JSON parse = JSONUtil.parse(Month.JANUARY);
@ -87,7 +87,7 @@ public class Issue2090Test {
@Test
public void weekTest(){
final JSONObject jsonObject = new JSONObject();
jsonObject.putObj("week", DayOfWeek.SUNDAY);
jsonObject.putValue("week", DayOfWeek.SUNDAY);
Assertions.assertEquals("{\"week\":7}", jsonObject.toString());
final JSON parse = JSONUtil.parse(DayOfWeek.SUNDAY);

View File

@ -60,7 +60,7 @@ public class Issue2555Test {
public static class MySerializer implements JSONSerializer<MyType> {
@Override
public JSON serialize(final MyType bean, final JSONContext context) {
return context.getOrCreateObj().putObj("addr", bean.getAddress());
return context.getOrCreateObj().putValue("addr", bean.getAddress());
}
}

View File

@ -34,7 +34,7 @@ public class Issue2572Test {
final Set<DayOfWeek> weeks = new HashSet<>();
weeks.add(DayOfWeek.MONDAY);
final JSONObject obj = new JSONObject();
obj.putObj("weeks", weeks);
obj.putValue("weeks", weeks);
Assertions.assertEquals("{\"weeks\":[1]}", obj.toString());
final Map<String, Set<DayOfWeek>> monthDays1 = obj.toBean(new TypeReference<Map<String, Set<DayOfWeek>>>() {
@ -47,7 +47,7 @@ public class Issue2572Test {
final Set<Month> months = new HashSet<>();
months.add(Month.DECEMBER);
final JSONObject obj = new JSONObject();
obj.putObj("months", months);
obj.putValue("months", months);
Assertions.assertEquals("{\"months\":[12]}", obj.toString());
final Map<String, Set<Month>> monthDays1 = obj.toBean(new TypeReference<Map<String, Set<Month>>>() {
@ -60,7 +60,7 @@ public class Issue2572Test {
final Set<MonthDay> monthDays = new HashSet<>();
monthDays.add(MonthDay.of(Month.DECEMBER, 1));
final JSONObject obj = new JSONObject();
obj.putObj("monthDays", monthDays);
obj.putValue("monthDays", monthDays);
Assertions.assertEquals("{\"monthDays\":[\"--12-01\"]}", obj.toString());
final Map<String, Set<MonthDay>> monthDays1 = obj.toBean(new TypeReference<Map<String, Set<MonthDay>>>() {

View File

@ -72,7 +72,7 @@ public class Issue3086Test {
public JSON serialize(final TestBean bean, final JSONContext context) {
final List<String> strings = bean.getAuthorities()
.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.toList());
return context.getOrCreateObj().putObj("authorities",strings);
return context.getOrCreateObj().putValue("authorities",strings);
}
}
}

View File

@ -26,8 +26,8 @@ public class IssueI3EGJPTest {
@Test
public void hutoolMapToBean() {
final JSONObject paramJson = new JSONObject();
paramJson.putObj("is_booleana", "1");
paramJson.putObj("is_booleanb", true);
paramJson.putValue("is_booleana", "1");
paramJson.putValue("is_booleanb", true);
final ConvertDO convertDO = paramJson.toBean(ConvertDO.class);
Assertions.assertTrue(convertDO.isBooleana());

View File

@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test;
public class IssueI59LW4Test {
@Test
public void bytesTest(){
final JSONObject jsonObject = JSONUtil.ofObj().putObj("bytes", new byte[]{1});
final JSONObject jsonObject = JSONUtil.ofObj().putValue("bytes", new byte[]{1});
Assertions.assertEquals("{\"bytes\":[1]}", jsonObject.toString());
final byte[] bytes = jsonObject.getBytes("bytes");
@ -34,7 +34,7 @@ public class IssueI59LW4Test {
@Test
public void bytesInJSONArrayTest(){
final JSONArray jsonArray = JSONUtil.ofArray().addObj(new byte[]{1});
final JSONArray jsonArray = JSONUtil.ofArray().addValue(new byte[]{1});
Assertions.assertEquals("[[1]]", jsonArray.toString());
final byte[] bytes = jsonArray.getBytes(0);

View File

@ -35,7 +35,7 @@ public class IssueI7VM64Test {
map.put("a", "1");
final JSONObject jsonObject = new JSONObject();
jsonObject.putObj("c", map);
jsonObject.putValue("c", map);
map.put("b", 2);
//Console.log("Hutool JSON: " + jsonObject);

View File

@ -29,7 +29,7 @@ public class Pr3507Test {
final JSONFactory factory = JSONFactory.of(null, null);
factory.register(Class.class, (JSONSerializer<Class<?>>) (bean, context) -> context.getOrCreatePrimitive(bean.getName()));
final JSONObject set = factory.ofObj().putObj("name", Pr3507Test.class);
final JSONObject set = factory.ofObj().putValue("name", Pr3507Test.class);
Assertions.assertEquals("{\"name\":\"org.dromara.hutool.json.issues.Pr3507Test\"}", set.toString());
}
}

View File

@ -1,5 +1,7 @@
package org.dromara.hutool.json.jmh;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.JsonObject;
import org.dromara.hutool.core.util.RandomUtil;
import org.dromara.hutool.json.JSONObject;
@ -25,6 +27,7 @@ public class JsonPutJmh {
private JSONObject hutoolJSON;
private JsonObject gson;
private com.alibaba.fastjson2.JSONObject fastJSON;
private ObjectNode jackson;
@Setup
@ -37,6 +40,7 @@ public class JsonPutJmh {
hutoolJSON = new JSONObject();
gson = new JsonObject();
fastJSON = new com.alibaba.fastjson2.JSONObject();
jackson = JsonNodeFactory.instance.objectNode();
}
@Benchmark
@ -46,11 +50,17 @@ public class JsonPutJmh {
@Benchmark
public void hutoolJmh() {
hutoolJSON.putAllObj(testData);
testData.forEach(hutoolJSON::putValue);
//hutoolJSON.putAllObj(testData);
}
@Benchmark
public void fastJSONJmh() {
fastJSON.putAll(testData);
}
@Benchmark
public void jacksonJmh(){
testData.forEach(jackson::put);
}
}

View File

@ -32,7 +32,7 @@ public class CustomSerializeTest {
TypeAdapterManager.getInstance().register(CustomBean.class,
(JSONSerializer<CustomBean>) (bean, context) ->{
final JSONObject contextJson = context.getOrCreateObj();
return contextJson.putObj("customName", bean.name);
return contextJson.putValue("customName", bean.name);
});
}
@ -50,7 +50,7 @@ public class CustomSerializeTest {
final CustomBean customBean = new CustomBean();
customBean.name = "testName";
final JSONObject obj = JSONUtil.ofObj().putObj("customBean", customBean);
final JSONObject obj = JSONUtil.ofObj().putValue("customBean", customBean);
Assertions.assertEquals("testName", obj.getJSONObject("customBean").getStr("customName"));
}

View File

@ -26,8 +26,8 @@ public class XMLTest {
@Test
public void toXmlTest(){
final JSONObject put = JSONUtil.ofObj()
.putObj("aaa", "你好")
.putObj("键2", "test");
.putValue("aaa", "你好")
.putValue("键2", "test");
final String s = JSONUtil.toXmlStr(put);
Assertions.assertEquals("<aaa>你好</aaa><键2>test</键2>", s);
}
@ -45,7 +45,7 @@ public class XMLTest {
@Test
public void xmlContentTest(){
final JSONObject jsonObject = JSONUtil.ofObj().putObj("content","123456");
final JSONObject jsonObject = JSONUtil.ofObj().putValue("content","123456");
String xml = JSONXMLUtil.toXml(jsonObject);
Assertions.assertEquals("123456", xml);
@ -56,7 +56,7 @@ public class XMLTest {
@Test
public void xmlContentTest2(){
final JSONObject jsonObject = JSONUtil.ofObj().putObj("content","123456");
final JSONObject jsonObject = JSONUtil.ofObj().putValue("content","123456");
final String xml = JSONXMLUtil.toXml(jsonObject, null, new String[0]);
Assertions.assertEquals("<content>123456</content>", xml);
}