This commit is contained in:
Looly
2024-09-28 02:01:20 +08:00
parent eecbf6ea29
commit 8eff63bc9f
35 changed files with 353 additions and 227 deletions

View File

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

View File

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

View File

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

View File

@@ -24,7 +24,6 @@ import org.dromara.hutool.core.map.CaseInsensitiveTreeMap;
import org.dromara.hutool.core.text.CharUtil; import org.dromara.hutool.core.text.CharUtil;
import org.dromara.hutool.core.text.StrUtil; import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil; import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.json.reader.JSONTokener;
import org.dromara.hutool.json.serializer.JSONMapper; import org.dromara.hutool.json.serializer.JSONMapper;
import java.io.IOException; import java.io.IOException;
@@ -104,25 +103,6 @@ public final class InternalJSONUtil {
return string; return string;
} }
/**
* 默认情况下是否忽略null值的策略选择以下对象不忽略null值其它对象忽略
*
* <pre>
* 1. CharSequence
* 2. JSONTokener
* 3. Map
* </pre>
*
* @param obj 需要检查的对象
* @return 是否忽略null值
* @since 4.3.1
*/
static boolean defaultIgnoreNullValue(final Object obj) {
return (!(obj instanceof CharSequence))//
&& (!(obj instanceof JSONTokener))//
&& (!(obj instanceof Map));
}
/** /**
* 将{@link JSONConfig}参数转换为Bean拷贝所用的{@link CopyOptions} * 将{@link JSONConfig}参数转换为Bean拷贝所用的{@link CopyOptions}
* *

View File

@@ -118,9 +118,8 @@ public class JSONArray extends ListWrapper<JSON> implements JSON, JSONGetter<Int
* *
* @param value 值,可以是: Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the JSONNull.NULL。 * @param value 值,可以是: Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the JSONNull.NULL。
* @return this. * @return this.
* @since 5.2.5
*/ */
public JSONArray set(final Object value) { public JSONArray addObj(final Object value) {
this.add(this.factory.getMapper().map(value)); this.add(this.factory.getMapper().map(value));
return this; return this;
} }
@@ -138,7 +137,7 @@ public class JSONArray extends ListWrapper<JSON> implements JSON, JSONGetter<Int
} }
final JSONObject jo = this.factory.ofObj(); final JSONObject jo = this.factory.ofObj();
for (int i = 0; i < names.size(); i += 1) { for (int i = 0; i < names.size(); i += 1) {
jo.set(names.getStr(i), this.getObj(i)); jo.putObj(names.getStr(i), this.getObj(i));
} }
return jo; return jo;
} }
@@ -169,10 +168,11 @@ public class JSONArray extends ListWrapper<JSON> implements JSON, JSONGetter<Int
* *
* @param index 位置 * @param index 位置
* @param element 值对象. 可以是以下类型: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull.NULL. * @param element 值对象. 可以是以下类型: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull.NULL.
* @return 替换的值,即之前的值 * @return this
*/ */
public JSON setValue(final int index, final Object element) { public JSONArray setObj(final int index, final Object element) {
return set(index, this.factory.getMapper().map(element)); set(index, this.factory.getMapper().map(element));
return this;
} }
/** /**
@@ -184,17 +184,32 @@ public class JSONArray extends ListWrapper<JSON> implements JSON, JSONGetter<Int
*/ */
@Override @Override
public JSON set(final int index, final JSON element) { public JSON set(final int index, final JSON element) {
// 越界则追加到指定位置
if (index >= size()) {
add(index, element);
return null;
}
if (null == element && config().isIgnoreNullValue()) { if (null == element && config().isIgnoreNullValue()) {
return null; return null;
} }
// 越界则追加到指定位置
final int size = size();
if(index == size){
add(element);
return null;
}
if (index > size) {
add(index, element);
return null;
}
return this.raw.set(index, element); return this.raw.set(index, element);
} }
@Override
public boolean add(final JSON element) {
if (null == element && config().isIgnoreNullValue()) {
return false;
}
return super.add(element);
}
@Override @Override
public void add(int index, final JSON element) { public void add(int index, final JSON element) {
final boolean ignoreNullValue = config().isIgnoreNullValue(); final boolean ignoreNullValue = config().isIgnoreNullValue();

View File

@@ -27,6 +27,7 @@ import org.dromara.hutool.json.writer.JSONWriter;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.function.Consumer;
import java.util.function.Predicate; import java.util.function.Predicate;
/** /**
@@ -66,7 +67,9 @@ public class JSONFactory {
private final JSONConfig config; private final JSONConfig config;
/** /**
* 过滤器,用于过滤或修改键值对返回null表示忽略此键值对返回非null表示修改后返回<br> * 过滤器,用于过滤或修改键值对<br>
* {@link Predicate#test(Object)} 返回{@code true}表示接受,{@code false}表示忽略<br>
* 同时{@link MutableEntry}为可变键值对,在判断逻辑中可同时修改键和值,修改后返回{@code true}<br>
* entry中key在JSONObject中为name在JSONArray中为index * entry中key在JSONObject中为name在JSONArray中为index
*/ */
private final Predicate<MutableEntry<Object, Object>> predicate; private final Predicate<MutableEntry<Object, Object>> predicate;
@@ -84,7 +87,7 @@ public class JSONFactory {
} }
/** /**
* 获取配置项 * 获取配置项,始终非空
* *
* @return 配置项 * @return 配置项
*/ */
@@ -93,7 +96,10 @@ public class JSONFactory {
} }
/** /**
* 获取键值对过滤器 * 获取键值对过滤器<br>
* {@link Predicate#test(Object)} 返回{@code true}表示接受,{@code false}表示忽略<br>
* 同时{@link MutableEntry}为可变键值对,在判断逻辑中可同时修改键和值,修改后返回{@code true}<br>
* entry中key在JSONObject中为name在JSONArray中为index
* *
* @return 键值对过滤器 * @return 键值对过滤器
*/ */
@@ -101,6 +107,26 @@ public class JSONFactory {
return this.predicate; return this.predicate;
} }
/**
* 执行键值对过滤,如果提供的键值对执行{@link Predicate#test(Object)}返回{@code false},则忽略此键值对;<br>
* 如果处理后返回{@code true}表示接受,调用{@link Consumer#accept(Object)}执行逻辑。<br>
* 如果用户未定义{@link #predicate},则接受所有键值对。
*
* @param entry 键值对
* @param consumer 键值对处理逻辑,如果处理后返回{@code true}表示接受,{@code false}表示忽略
*/
public void doPredicate(final MutableEntry<Object, Object> entry,
final Consumer<MutableEntry<Object, Object>> consumer) {
final Predicate<MutableEntry<Object, Object>> predicate = this.predicate;
if (null != predicate && !predicate.test(entry)) {
// 过滤键值对
return;
}
// 键值对处理
consumer.accept(entry);
}
/** /**
* 获取{@link JSONMapper}用于实现Bean和JSON的转换<br> * 获取{@link JSONMapper}用于实现Bean和JSON的转换<br>
* 此方法使用双重检查锁实现懒加载模式只有mapper被使用时才初始化 * 此方法使用双重检查锁实现懒加载模式只有mapper被使用时才初始化
@@ -154,7 +180,7 @@ public class JSONFactory {
* @param tokener {@link JSONTokener} * @param tokener {@link JSONTokener}
* @return {@link JSONParser} * @return {@link JSONParser}
*/ */
public JSONParser ofParser(final JSONTokener tokener){ public JSONParser ofParser(final JSONTokener tokener) {
return JSONParser.of(tokener, this); return JSONParser.of(tokener, this);
} }

View File

@@ -143,7 +143,7 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGe
} }
// endregion // endregion
// region ----- set // region ----- put
/** /**
* 对值加一如果值不存在赋值1如果为数字类型做加一操作 * 对值加一如果值不存在赋值1如果为数字类型做加一操作
* *
@@ -154,7 +154,7 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGe
public JSONObject increment(final String key) throws JSONException { public JSONObject increment(final String key) throws JSONException {
final JSON json = this.get(key); final JSON json = this.get(key);
if(null == json){ if(null == json){
return set(key, 1); return putObj(key, 1);
} }
if(json instanceof JSONPrimitive){ if(json instanceof JSONPrimitive){
@@ -185,11 +185,11 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGe
public JSONObject append(final String key, final Object value) throws JSONException { public JSONObject append(final String key, final Object value) throws JSONException {
final Object object = this.getObj(key); final Object object = this.getObj(key);
if (object == null) { if (object == null) {
this.set(key, value); this.putObj(key, value);
} else if (object instanceof JSONArray) { } else if (object instanceof JSONArray) {
((JSONArray) object).set(value); ((JSONArray) object).addObj(value);
} else { } else {
this.set(key, factory.ofArray().set(object).set(value)); this.putObj(key, factory.ofArray().addObj(object).addObj(value));
} }
return this; return this;
} }
@@ -205,8 +205,8 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGe
* @param fields lambda,不能为空 * @param fields lambda,不能为空
* @return this * @return this
*/ */
public JSONObject setFields(final SerSupplier<?>... fields) { public JSONObject putFields(final SerSupplier<?>... fields) {
Arrays.stream(fields).forEach(f -> set(LambdaUtil.getFieldName(f), f.get())); Arrays.stream(fields).forEach(f -> putObj(LambdaUtil.getFieldName(f), f.get()));
return this; return this;
} }
@@ -217,10 +217,10 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGe
* @return this. * @return this.
* @throws JSONException 值是无穷数字抛出此异常 * @throws JSONException 值是无穷数字抛出此异常
*/ */
public JSONObject setAll(final Map<?, ?> map) { public JSONObject putAllObj(final Map<?, ?> map) {
if(MapUtil.isNotEmpty(map)){ if(MapUtil.isNotEmpty(map)){
for (final Entry<?, ?> entry : map.entrySet()) { for (final Entry<?, ?> entry : map.entrySet()) {
this.set(StrUtil.toStringOrNull(entry.getKey()), entry.getValue()); this.putObj(StrUtil.toStringOrNull(entry.getKey()), entry.getValue());
} }
} }
return this; return this;
@@ -234,7 +234,7 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGe
* @return this. * @return this.
* @throws JSONException 值是无穷数字抛出此异常 * @throws JSONException 值是无穷数字抛出此异常
*/ */
public JSONObject set(final String key, final Object value) throws JSONException { public JSONObject putObj(final String key, final Object value) throws JSONException {
this.put(key, factory.getMapper().map(value)); this.put(key, factory.getMapper().map(value));
return this; return this;
} }

View File

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

View File

@@ -165,20 +165,8 @@ public class JSONParser {
// The key is followed by ':'. // The key is followed by ':'.
tokener.nextColon(); tokener.nextColon();
// 过滤并设置键值对 // 过滤并设置键值对通过MutablePair实现过滤、修改键值对等
final JSON value = nextJSON(tokener.nextClean()); set(jsonObject, key, nextJSON(tokener.nextClean()));
// 添加前置过滤通过MutablePair实现过滤、修改键值对等
final Predicate<MutableEntry<Object, Object>> predicate = factory.getPredicate();
if (null != predicate) {
final MutableEntry<Object, Object> entry = new MutableEntry<>(key, value);
if (predicate.test(entry)) {
// 使用修改后的键值对
key = (String) entry.getKey();
jsonObject.set(key, entry.getValue());
}
} else {
jsonObject.set(key, value);
}
// Pairs are separated by ',' or ';' // Pairs are separated by ',' or ';'
switch (tokener.nextClean()) { switch (tokener.nextClean()) {
@@ -199,6 +187,27 @@ public class JSONParser {
} }
} }
/**
* 设置键值对,通过前置过滤器过滤、修改键值对等
*
* @param jsonObject JSON对象
* @param key 键
* @param value 值
*/
private void set(final JSONObject jsonObject, final String key, final JSON value){
// 添加前置过滤通过MutablePair实现过滤、修改键值对等
final Predicate<MutableEntry<Object, Object>> predicate = factory.getPredicate();
if (null != predicate) {
final MutableEntry<Object, Object> entry = new MutableEntry<>(key, value);
if (predicate.test(entry)) {
// 使用修改后的键值对
jsonObject.putObj((String) entry.getKey(), entry.getValue());
}
} else {
jsonObject.put(key, value);
}
}
/** /**
* 解析下一个值为JSONArray第一个字符必须读取完后再调用此方法 * 解析下一个值为JSONArray第一个字符必须读取完后再调用此方法
* *
@@ -214,23 +223,31 @@ public class JSONParser {
return; return;
} else { } else {
// ,value or value // ,value or value
JSON value = nextJSON(CharUtil.COMMA == c ? tokener.nextClean() : c); set(jsonArray, nextJSON(CharUtil.COMMA == c ? tokener.nextClean() : c));
final Predicate<MutableEntry<Object, Object>> predicate = factory.getPredicate();
if (null != predicate) {
// 使用过滤器
final MutableEntry<Object, Object> entry = MutableEntry.of(jsonArray.size(), value);
if (predicate.test(entry)) {
// 使用修改后的键值对
value = (JSON) entry.getValue();
jsonArray.add(value);
}
} else {
jsonArray.add(value);
}
} }
} }
} }
/**
* 设置数组元素,通过前置过滤器过滤、修改键值对等
*
* @param jsonArray JSON数组
* @param value 值
*/
private void set(final JSONArray jsonArray, final JSON value) {
final Predicate<MutableEntry<Object, Object>> predicate = factory.getPredicate();
if (null != predicate) {
// 使用过滤器
final MutableEntry<Object, Object> entry = MutableEntry.of(jsonArray.size(), value);
if (predicate.test(entry)) {
// 使用修改后的键值对用户修改后可能不是JSON此处使用set调用mapper转换
jsonArray.setObj((Integer) entry.getKey(), entry.getValue());
}
} else {
jsonArray.add(value);
}
}
/** /**
* 解析为JSONPrimitive或{@code null},解析值包括: * 解析为JSONPrimitive或{@code null},解析值包括:
* <pre> * <pre>

View File

@@ -147,7 +147,7 @@ public class JSONMapper implements Serializable {
public JSONArray mapFromJSONObject(final JSONObject jsonObject) { public JSONArray mapFromJSONObject(final JSONObject jsonObject) {
final JSONArray array = factory.ofArray(); final JSONArray array = factory.ofArray();
for (final Map.Entry<String, JSON> entry : jsonObject) { for (final Map.Entry<String, JSON> entry : jsonObject) {
array.set(entry); array.addObj(entry);
} }
return array; return array;
} }

View File

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

View File

@@ -18,7 +18,6 @@ package org.dromara.hutool.json.serializer.impl;
import org.dromara.hutool.core.bean.BeanDesc; import org.dromara.hutool.core.bean.BeanDesc;
import org.dromara.hutool.core.bean.BeanUtil; import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.bean.copier.BeanToMapCopier;
import org.dromara.hutool.core.bean.copier.ValueProviderToBeanCopier; import org.dromara.hutool.core.bean.copier.ValueProviderToBeanCopier;
import org.dromara.hutool.core.lang.copier.Copier; import org.dromara.hutool.core.lang.copier.Copier;
import org.dromara.hutool.core.reflect.ConstructorUtil; import org.dromara.hutool.core.reflect.ConstructorUtil;
@@ -31,6 +30,7 @@ import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.serializer.JSONContext; import org.dromara.hutool.json.serializer.JSONContext;
import org.dromara.hutool.json.serializer.MatcherJSONDeserializer; import org.dromara.hutool.json.serializer.MatcherJSONDeserializer;
import org.dromara.hutool.json.serializer.MatcherJSONSerializer; import org.dromara.hutool.json.serializer.MatcherJSONSerializer;
import org.dromara.hutool.json.support.BeanToJSONCopier;
import org.dromara.hutool.json.support.JSONObjectValueProvider; import org.dromara.hutool.json.support.JSONObjectValueProvider;
import java.lang.reflect.Type; import java.lang.reflect.Type;
@@ -72,14 +72,9 @@ public class BeanTypeAdapter implements MatcherJSONSerializer<Object>, MatcherJS
@Override @Override
public JSON serialize(final Object bean, final JSONContext context) { public JSON serialize(final Object bean, final JSONContext context) {
final JSONObject contextJson = context.getOrCreateObj(); final BeanToJSONCopier copier = new BeanToJSONCopier(
bean, context.getOrCreateObj(), context.getFactory());
final BeanToMapCopier copier = new BeanToMapCopier( return copier.copy();
bean,
contextJson,
JSONObject.class, InternalJSONUtil.toCopyOptions(context.config())
);
return (JSON) copier.copy();
} }
@Override @Override

View File

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

View File

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

View File

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

View File

@@ -87,10 +87,10 @@ public class ResourceBundleSerializer implements MatcherJSONSerializer<ResourceB
JSONObject nextTarget = target.getJSONObject(segment); JSONObject nextTarget = target.getJSONObject(segment);
if (nextTarget == null) { if (nextTarget == null) {
nextTarget = JSONUtil.ofObj(target.config()); nextTarget = JSONUtil.ofObj(target.config());
target.set(segment, nextTarget); target.putObj(segment, nextTarget);
} }
target = nextTarget; target = nextTarget;
} }
target.set(path[last], value); target.putObj(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) { private static void toJSONObject(final TemporalAccessor bean, final JSONObject json) {
if (bean instanceof LocalDate) { if (bean instanceof LocalDate) {
final LocalDate localDate = (LocalDate) bean; final LocalDate localDate = (LocalDate) bean;
json.set(YEAR_KEY, localDate.getYear()); json.putObj(YEAR_KEY, localDate.getYear());
json.set(MONTH_KEY, localDate.getMonthValue()); json.putObj(MONTH_KEY, localDate.getMonthValue());
json.set(DAY_KEY, localDate.getDayOfMonth()); json.putObj(DAY_KEY, localDate.getDayOfMonth());
} else if (bean instanceof LocalDateTime) { } else if (bean instanceof LocalDateTime) {
final LocalDateTime localDateTime = (LocalDateTime) bean; final LocalDateTime localDateTime = (LocalDateTime) bean;
json.set(YEAR_KEY, localDateTime.getYear()); json.putObj(YEAR_KEY, localDateTime.getYear());
json.set(MONTH_KEY, localDateTime.getMonthValue()); json.putObj(MONTH_KEY, localDateTime.getMonthValue());
json.set(DAY_KEY, localDateTime.getDayOfMonth()); json.putObj(DAY_KEY, localDateTime.getDayOfMonth());
json.set(HOUR_KEY, localDateTime.getHour()); json.putObj(HOUR_KEY, localDateTime.getHour());
json.set(MINUTE_KEY, localDateTime.getMinute()); json.putObj(MINUTE_KEY, localDateTime.getMinute());
json.set(SECOND_KEY, localDateTime.getSecond()); json.putObj(SECOND_KEY, localDateTime.getSecond());
json.set(NANO_KEY, localDateTime.getNano()); json.putObj(NANO_KEY, localDateTime.getNano());
} else if (bean instanceof LocalTime) { } else if (bean instanceof LocalTime) {
final LocalTime localTime = (LocalTime) bean; final LocalTime localTime = (LocalTime) bean;
json.set(HOUR_KEY, localTime.getHour()); json.putObj(HOUR_KEY, localTime.getHour());
json.set(MINUTE_KEY, localTime.getMinute()); json.putObj(MINUTE_KEY, localTime.getMinute());
json.set(SECOND_KEY, localTime.getSecond()); json.putObj(SECOND_KEY, localTime.getSecond());
json.set(NANO_KEY, localTime.getNano()); json.putObj(NANO_KEY, localTime.getNano());
} else{ } else{
throw new JSONException("Unsupported type: {}", bean.getClass().getName()); throw new JSONException("Unsupported type: {}", bean.getClass().getName());
} }

View File

@@ -0,0 +1,93 @@
/*
* Copyright (c) 2024 Hutool Team and hutool.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.hutool.json.support;
import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.bean.PropDesc;
import org.dromara.hutool.core.lang.copier.Copier;
import org.dromara.hutool.core.lang.mutable.MutableEntry;
import org.dromara.hutool.json.JSONConfig;
import org.dromara.hutool.json.JSONFactory;
import org.dromara.hutool.json.JSONObject;
import java.util.Map;
import java.util.function.Predicate;
/**
* Bean转JSON对象复制器
*
* @author looly
* @since 6.0.0
*/
public class BeanToJSONCopier implements Copier<JSONObject> {
private final Object source;
private final JSONObject target;
private final JSONFactory factory;
/**
* 构造
*
* @param source 源对象
* @param target 目标JSON
* @param factory JSON工厂
*/
public BeanToJSONCopier(final Object source, final JSONObject target, final JSONFactory factory) {
this.source = source;
this.target = target;
this.factory = factory;
}
@Override
public JSONObject copy() {
final JSONConfig config = factory.getConfig();
final Map<String, PropDesc> sourcePropDescMap = BeanUtil.getBeanDesc(source.getClass())
.getPropMap(config.isIgnoreCase());
sourcePropDescMap.forEach((sFieldName, sDesc) -> {
if (null == sFieldName || !sDesc.isReadable(config.isTransientSupport())) {
// 字段空或不可读,跳过
return;
}
final Object sValue = sDesc.getValue(this.source, config.isIgnoreError());
putValue(sFieldName, sValue, config.isIgnoreNullValue());
});
return target;
}
/**
* 赋值,过滤则跳过
*
* @param fieldName 字段名
* @param sValue 源值
* @param ignoreNullValue 是否忽略null值
*/
private void putValue(final String fieldName, final Object sValue, final boolean ignoreNullValue) {
final Predicate<MutableEntry<Object, Object>> predicate = factory.getPredicate();
if (null != predicate) {
final MutableEntry<Object, Object> entry = new MutableEntry<>(fieldName, sValue);
if (predicate.test(entry)) {
// 使用修改后的键值对
target.putObj((String) entry.getKey(), entry.getValue());
}
} else if (null != sValue || !ignoreNullValue) {
target.putObj(fieldName, sValue);
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -22,7 +22,7 @@ import org.junit.jupiter.api.Test;
public class Pr3507Test { public class Pr3507Test {
@Test @Test
void writeClassTest() { void writeClassTest() {
final JSONObject set = JSONUtil.ofObj().set("name", Pr3507Test.class); final JSONObject set = JSONUtil.ofObj().putObj("name", Pr3507Test.class);
Assertions.assertEquals("{\"name\":\"org.dromara.hutool.json.Pr3507Test\"}", set.toString()); Assertions.assertEquals("{\"name\":\"org.dromara.hutool.json.Pr3507Test\"}", set.toString());
} }
} }

View File

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