This commit is contained in:
Looly 2024-09-18 20:41:23 +08:00
parent 71019b6935
commit c489cc7735
78 changed files with 672 additions and 890 deletions

View File

@ -309,6 +309,7 @@ public class BeanUtil {
/**
* 将Bean包装为Map形式
*
* @param bean Bean
* @return {@link BeanMap}
* @since 6.0.0
@ -391,6 +392,7 @@ public class BeanUtil {
* 3. 自定义字段前缀或后缀等等
* </pre>
*
* @param <V> Map中值类型
* @param bean bean对象
* @param targetMap 目标的Map
* @param ignoreNullValue 是否忽略值为空的字段
@ -398,8 +400,8 @@ public class BeanUtil {
* @return Map
* @since 4.0.5
*/
public static Map<String, Object> beanToMap(final Object bean,
final Map<String, Object> targetMap,
public static <V> Map<String, V> beanToMap(final Object bean,
final Map<String, V> targetMap,
final boolean ignoreNullValue,
final UnaryOperator<MutableEntry<Object, Object>> keyEditor) {
if (null == bean) {
@ -425,13 +427,14 @@ public class BeanUtil {
* ...
* </pre>
*
* @param <V> Map中值类型
* @param bean bean对象
* @param targetMap 目标的Map
* @param copyOptions 拷贝选项
* @return Map
* @since 5.7.15
*/
public static Map<String, Object> beanToMap(final Object bean, final Map<String, Object> targetMap, final CopyOptions copyOptions) {
public static <V> Map<String, V> beanToMap(final Object bean, final Map<String, V> targetMap, final CopyOptions copyOptions) {
if (null == bean) {
return null;
}

View File

@ -19,8 +19,10 @@ package org.dromara.hutool.core.convert.impl;
import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.convert.ConvertException;
import org.dromara.hutool.core.convert.Converter;
import org.dromara.hutool.core.convert.ConverterWithRoot;
import org.dromara.hutool.core.convert.MatcherConverter;
import org.dromara.hutool.core.lang.tuple.Pair;
import org.dromara.hutool.core.lang.wrapper.Wrapper;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.reflect.ConstructorUtil;
import org.dromara.hutool.core.reflect.TypeReference;
@ -43,18 +45,16 @@ import java.util.Map;
*
* @author looly
*/
public class EntryConverter implements MatcherConverter, Serializable {
public class EntryConverter extends ConverterWithRoot implements MatcherConverter, Serializable {
private static final long serialVersionUID = 1L;
private final Converter convert;
/**
* 构造
*
* @param converter 转换器用于将Entry中key和value转换为指定类型的对象
*/
public EntryConverter(final Converter converter) {
this.convert = converter;
super(converter);
}
@Override
@ -141,7 +141,7 @@ public class EntryConverter implements MatcherConverter, Serializable {
private Map.Entry<?, ?> mapToEntry(final Type targetType, final Type keyType, final Type valueType, final Map map) {
final Object key;
final Object value;
Object value;
if (1 == map.size()) {
final Map.Entry entry = (Map.Entry) map.entrySet().iterator().next();
key = entry.getKey();
@ -152,9 +152,13 @@ public class EntryConverter implements MatcherConverter, Serializable {
value = map.get("value");
}
if(value instanceof Wrapper){
value = ((Wrapper) value).getRaw();
}
return (Map.Entry<?, ?>) ConstructorUtil.newInstance(TypeUtil.getClass(targetType),
TypeUtil.isUnknown(keyType) ? key : convert.convert(keyType, key),
TypeUtil.isUnknown(valueType) ? value : convert.convert(valueType, value)
TypeUtil.isUnknown(keyType) ? key : rootConverter.convert(keyType, key),
TypeUtil.isUnknown(valueType) ? value : rootConverter.convert(valueType, value)
);
}
}

View File

@ -82,8 +82,7 @@ public class MapConverter extends ConverterWithRoot implements MatcherConverter,
* @throws ConvertException 转换异常或不支持的类型
*/
@SuppressWarnings("rawtypes")
public Map<?, ?> convert(final Type targetType, final Type keyType, final Type valueType, final Object value)
throws ConvertException{
public Map<?, ?> convert(final Type targetType, final Type keyType, final Type valueType, final Object value) throws ConvertException{
Map map;
if (value instanceof Map) {
final Class<?> valueClass = value.getClass();

View File

@ -19,7 +19,7 @@ package org.dromara.hutool.http;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.net.url.UrlQuery;
import org.dromara.hutool.core.util.CharsetUtil;
import org.dromara.hutool.json.OldJSONObject;
import org.dromara.hutool.json.JSONObject;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -30,8 +30,8 @@ public class IssueIAFKWPTest {
@Test
void urlWithFormTest() {
final OldJSONObject obj = new OldJSONObject();
obj.put("fields", ListUtil.of("1", "2", "good"));
final JSONObject obj = new JSONObject();
obj.set("fields", ListUtil.of("1", "2", "good"));
final Map<String, Object> params = new HashMap<>();
params.put("query", obj.toString());

View File

@ -21,7 +21,6 @@ import org.dromara.hutool.core.bean.copier.CopyOptions;
import org.dromara.hutool.core.codec.binary.HexUtil;
import org.dromara.hutool.core.convert.ConvertUtil;
import org.dromara.hutool.core.io.IORuntimeException;
import org.dromara.hutool.core.lang.mutable.MutableEntry;
import org.dromara.hutool.core.map.CaseInsensitiveLinkedMap;
import org.dromara.hutool.core.map.CaseInsensitiveTreeMap;
import org.dromara.hutool.core.math.NumberUtil;
@ -34,7 +33,6 @@ import org.dromara.hutool.json.reader.JSONTokener;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Predicate;
/**
* 内部JSON工具类仅用于JSON内部使用
@ -93,7 +91,7 @@ public final class InternalJSONUtil {
* 值转为String用于JSON中规则为
* <ul>
* <li>对象如果是数组或Collection包装为{@link JSONArray}</li>
* <li>对象如果是Map包装为{@link OldJSONObject}</li>
* <li>对象如果是Map包装为{@link JSONObject}</li>
* <li>对象如果是数字使用{@link NumberUtil#toStr(Number)}转换为字符串</li>
* <li>其他情况调用toString并使用双引号包装</li>
* </ul>
@ -108,11 +106,11 @@ public final class InternalJSONUtil {
}
if (value instanceof Number) {
return NumberUtil.toStr((Number) value);
} else if (value instanceof Boolean || value instanceof OldJSONObject || value instanceof JSONArray) {
} else if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) {
return value.toString();
} else if (value instanceof Map) {
final Map<?, ?> map = (Map<?, ?>) value;
return new OldJSONObject(map).toString();
return JSONUtil.parseObj(map).toString();
} else if (value instanceof Collection) {
final Collection<?> coll = (Collection<?>) value;
return new JSONArray(coll).toString();
@ -131,22 +129,21 @@ public final class InternalJSONUtil {
* @param jsonObject JSONObject
* @param key
* @param value
* @param predicate 属性过滤器{@link Predicate#test(Object)}{@code true}保留
*/
public static void propertyPut(final OldJSONObject jsonObject, final Object key, final Object value, final Predicate<MutableEntry<Object, Object>> predicate) {
public static void propertyPut(final JSONObject jsonObject, final Object key, final Object value) {
final String[] path = SplitUtil.splitToArray(ConvertUtil.toStr(key), StrUtil.DOT);
final int last = path.length - 1;
OldJSONObject target = jsonObject;
JSONObject target = jsonObject;
for (int i = 0; i < last; i += 1) {
final String segment = path[i];
OldJSONObject nextTarget = target.getJSONObject(segment);
JSONObject nextTarget = target.getJSONObject(segment);
if (nextTarget == null) {
nextTarget = new OldJSONObject(target.config());
target.set(segment, nextTarget, predicate);
nextTarget = new JSONObject(target.config());
target.set(segment, nextTarget);
}
target = nextTarget;
}
target.set(path[last], value, predicate);
target.set(path[last], value);
}
/**
@ -265,36 +262,6 @@ public final class InternalJSONUtil {
return builder.toString();
}
/**
* 根据配置创建对应的原始Map
*
* @param capacity 初始大小
* @param config JSON配置项{@code null}则使用默认配置
* @return Map
*/
@Deprecated
static Map<String, Object> createRawMapOld(final int capacity, JSONConfig config) {
final Map<String, Object> rawHashMap;
if (null == config) {
config = JSONConfig.of();
}
final Comparator<String> keyComparator = config.getKeyComparator();
if (config.isIgnoreCase()) {
if (null != keyComparator) {
rawHashMap = new CaseInsensitiveTreeMap<>(keyComparator);
} else {
rawHashMap = new CaseInsensitiveLinkedMap<>(capacity);
}
} else {
if (null != keyComparator) {
rawHashMap = new TreeMap<>(keyComparator);
} else {
rawHashMap = new LinkedHashMap<>(capacity);
}
}
return rawHashMap;
}
/**
* 根据配置创建对应的原始Map
*

View File

@ -19,16 +19,18 @@ package org.dromara.hutool.json;
import org.dromara.hutool.core.bean.path.BeanPath;
import org.dromara.hutool.core.convert.ConvertException;
import org.dromara.hutool.core.convert.Converter;
import org.dromara.hutool.core.lang.mutable.MutableEntry;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.json.writer.JSONWriter;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.function.Predicate;
/**
* JSON树模型接口表示树中的一个节点实现包括
* <ul>
* <li>{@link OldJSONObject}表示键值对形式的节点</li>
* <li>{@link JSONObject}表示键值对形式的节点</li>
* <li>{@link JSONArray}表示列表形式的节点</li>
* <li>{@link JSONPrimitive}表示数字Boolean字符串形式的节点</li>
* <li>{@code null}表示空节点</li>
@ -53,6 +55,15 @@ public interface JSON extends Converter, Cloneable, Serializable {
*/
int size();
/**
* 判断JSON是否为空即大小为0
*
* @return 是否为空
*/
default boolean isEmpty() {
return 0 == size();
}
/**
* 通过表达式获取JSON中嵌套的对象<br>
* <ol>
@ -152,7 +163,19 @@ public interface JSON extends Converter, Cloneable, Serializable {
* @throws JSONException 包含非法数抛出此异常
*/
default String toJSONString(final int indentFactor) throws JSONException {
final JSONWriter jsonWriter = JSONWriter.of(new StringBuilder(), indentFactor, 0, config());
return toJSONString(indentFactor, null);
}
/**
* 格式化输出JSON字符串
*
* @param indentFactor 每层缩进空格数
* @param predicate 过滤器用于过滤不需要的键值对
* @return JSON字符串
* @throws JSONException 包含非法数抛出此异常
*/
default String toJSONString(final int indentFactor, final Predicate<MutableEntry<Object, Object>> predicate) throws JSONException {
final JSONWriter jsonWriter = JSONWriter.of(new StringBuilder(), indentFactor, 0, config()).setPredicate(predicate);
this.write(jsonWriter);
return jsonWriter.toString();
}

View File

@ -257,11 +257,11 @@ public class JSONArray implements JSON, JSONGetter<Integer>, List<Object>, Rando
* @return A JSONObject无名或值返回null
* @throws JSONException 如果任何一个名为null
*/
public OldJSONObject toJSONObject(final JSONArray names) throws JSONException {
public JSONObject toJSONObject(final JSONArray names) throws JSONException {
if (names == null || names.size() == 0 || this.size() == 0) {
return null;
}
final OldJSONObject jo = new OldJSONObject(this.config);
final JSONObject jo = new JSONObject(this.config);
for (int i = 0; i < names.size(); i += 1) {
jo.set(names.getStr(i), this.getObj(i));
}
@ -569,7 +569,7 @@ public class JSONArray implements JSON, JSONGetter<Integer>, List<Object>, Rando
@Override
public void write(final JSONWriter writer) throws JSONException {
final JSONWriter copyWriter = writer.copyOf();
final JSONWriter copyWriter = writer.copyOfSub();
copyWriter.beginArray();
CollUtil.forEach(this, (value, index) -> copyWriter.writeField(new MutableEntry<>(index, value)));
copyWriter.end();

View File

@ -92,21 +92,22 @@ public interface JSONGetter<K> extends TypeGetter<K> {
/**
* 获得JSONObject对象<br>
* 如果值为其它类型对象尝试转换为{@link OldJSONObject}返回否则抛出异常
* 如果值为其它类型对象尝试转换为{@link JSONObject}返回否则抛出异常
*
* @param key KEY
* @return JSONObject对象如果值为{@code null}返回{@code null}非JSONObject类型尝试转换转换失败抛出异常
*/
default OldJSONObject getJSONObject(final K key) {
final Object object = this.getObj(key);
if (ObjUtil.isNull(object)) {
default JSONObject getJSONObject(final K key) {
final Object obj = getObj(key);
if(null == obj){
return null;
}
if (object instanceof JSON) {
return (OldJSONObject) object;
if(obj instanceof JSONObject){
return (JSONObject) obj;
}
return new OldJSONObject(object, config());
throw new JSONException("JSONObject expected, but " + obj.getClass());
}
/**
@ -119,9 +120,13 @@ public interface JSONGetter<K> extends TypeGetter<K> {
* @return Bean对象如果值为null或者非JSONObject类型返回null
* @since 3.1.1
*/
@SuppressWarnings("unchecked")
default <T> T getBean(final K key, final Class<T> beanType) {
final OldJSONObject obj = getJSONObject(key);
return (null == obj) ? null : obj.toBean(beanType);
final Object obj = getObj(key);
if(null == obj || beanType.isInstance(obj)){
return (T) obj;
}
return ((JSON)obj).toBean(beanType);
}
/**

View File

@ -16,13 +16,33 @@
package org.dromara.hutool.json;
import org.dromara.hutool.core.func.LambdaInfo;
import org.dromara.hutool.core.func.LambdaUtil;
import org.dromara.hutool.core.func.SerFunction;
import org.dromara.hutool.core.func.SerSupplier;
import org.dromara.hutool.core.lang.mutable.MutableEntry;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.map.MapWrapper;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.json.mapper.JSONValueMapper;
import org.dromara.hutool.json.writer.JSONWriter;
public class JSONObject extends MapWrapper<String, JSON> implements JSON{
import java.util.Arrays;
import java.util.Map;
/**
* JSON对象<br>
* 对象是 JSON 中的映射类型他们将映射到 JSON 必须始终是字符串这些对中的每一组通常被称为属性<br>
*
* <pre>{@code
* json = new JSONObject().put("JSON", "Hello, World!").toString();
* }</pre>
*
* @author looly
*/
public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGetter<String>{
private static final long serialVersionUID = 1L;
/**
* 默认初始大小
@ -32,7 +52,11 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON{
/**
* 配置项
*/
private JSONConfig config;
private final JSONConfig config;
/**
* 对象转换和包装用于将Java对象和值转换为JSON值
*/
private final JSONValueMapper valueMapper;
/**
* 构造初始容量为 {@link #DEFAULT_CAPACITY}KEY有序
@ -60,6 +84,7 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON{
public JSONObject(final int capacity, final JSONConfig config) {
super(InternalJSONUtil.createRawMap(capacity, config));
this.config = ObjUtil.defaultIfNull(config, JSONConfig::of);
this.valueMapper = JSONValueMapper.of(this.config);
}
@Override
@ -69,8 +94,169 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON{
@Override
public void write(final JSONWriter writer) throws JSONException {
writer.beginObj();
this.forEach((key, value) -> writer.writeField(new MutableEntry<>(key, value)));
writer.end();
final JSONWriter jsonWriter = writer.copyOfSub();
jsonWriter.beginObj();
this.forEach((key, value) -> jsonWriter.writeField(new MutableEntry<>(key, value)));
jsonWriter.end();
}
// region ----- get
/**
* 根据lambda的方法引用获取
*
* @param func 方法引用
* @param <P> 参数类型
* @param <T> 返回值类型
* @return 获取表达式对应属性和返回的对象
*/
public <P, T> T get(final SerFunction<P, T> func) {
final LambdaInfo lambdaInfo = LambdaUtil.resolve(func);
return get(lambdaInfo.getFieldName(), lambdaInfo.getReturnType());
}
@Override
public Object getObj(final String key, final Object defaultValue) {
final Object value;
final JSON json = get(key);
if(json instanceof JSONPrimitive){
value = ((JSONPrimitive) json).getValue();
}else {
value = json;
}
return ObjUtil.defaultIfNull(value, defaultValue);
}
@Override
public JSON get(final Object key) {
return super.get(key);
}
// endregion
// region ----- set
/**
* 对值加一如果值不存在赋值1如果为数字类型做加一操作
*
* @param key A key string.
* @return this.
* @throws JSONException 如果存在值非Integer, Long, Double, Float.
*/
public JSONObject increment(final String key) throws JSONException {
final JSON json = this.get(key);
if(null == json){
return set(key, 1);
}
if(json instanceof JSONPrimitive){
final JSONPrimitive jsonPrimitive = (JSONPrimitive) json;
if(jsonPrimitive.isNumber()){
jsonPrimitive.increment();
return this;
}
}
throw new JSONException("Unable to increment key: {} type: {}", key, json.getClass());
}
/**
* 追加值.
* <ul>
* <li>如果键值对不存在或对应值为{@code null}则value为单独值</li>
* <li>如果值是一个{@link JSONArray}追加之</li>
* <li>如果值是一个其他值则和旧值共同组合为一个{@link JSONArray}</li>
* </ul>
*
* @param key
* @param value
* @return this.
* @throws JSONException 如果给定键为{@code null}或者键对应的值存在且为非JSONArray
* @since 6.0.0
*/
public JSONObject append(final String key, final Object value) throws JSONException {
final Object object = this.getObj(key);
if (object == null) {
this.set(key, value);
} else if (object instanceof JSONArray) {
((JSONArray) object).set(value);
} else {
this.set(key, JSONUtil.ofArray(this.config).set(object).set(value));
}
return this;
}
/**
* 通过lambda批量设置值<br>
* 实际使用时可以使用getXXX的方法引用来完成键值对的赋值
* <pre>{@code
* User user = GenericBuilder.of(User::new).with(User::setUsername, "hutool").build();
* (new JSONObject()).setFields(user::getNickname, user::getUsername);
* }</pre>
*
* @param fields lambda,不能为空
* @return this
*/
public JSONObject setFields(final SerSupplier<?>... fields) {
Arrays.stream(fields).forEach(f -> set(LambdaUtil.getFieldName(f), f.get()));
return this;
}
/**
* 设置所有键值对到JSONObject中在忽略null模式下如果值为{@code null}将此键移除
*
* @param map 键值对
* @return this.
* @throws JSONException 值是无穷数字抛出此异常
*/
public JSONObject setAll(final Map<?, ?> map) {
if(MapUtil.isNotEmpty(map)){
for (final Entry<?, ?> entry : map.entrySet()) {
this.set(StrUtil.toStringOrNull(entry.getKey()), entry.getValue());
}
}
return this;
}
/**
* 设置键值对到JSONObject中在忽略null模式下如果值为{@code null}将此键移除
*
* @param key
* @param value 值对象. 可以是以下类型: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull.NULL.
* @return this.
* @throws JSONException 值是无穷数字抛出此异常
*/
public JSONObject set(final String key, final Object value) throws JSONException {
this.put(key, valueMapper.map(value));
return this;
}
/**
* 设置键值对到JSONObject中在忽略null模式下如果值为{@code null}将此键移除
*
* @param key
* @param value 值对象. 可以是以下类型: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull.NULL.
* @return 旧值
* @throws JSONException 值是无穷数字抛出此异常
*/
@Override
public JSON put(final String key, final JSON value) throws JSONException {
if (null == key) {
return null;
}
final boolean ignoreNullValue = this.config.isIgnoreNullValue();
if (null == value && ignoreNullValue) {
// 忽略值模式下如果值为空清除key
return this.remove(key);
} else if (this.config.isCheckDuplicate() && containsKey(key)) {
throw new JSONException("Duplicate key \"{}\"", key);
}
return super.put(key, value);
}
// endregion
@Override
public String toString() {
return toJSONString(0);
}
}

View File

@ -17,11 +17,14 @@
package org.dromara.hutool.json;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.lang.wrapper.Wrapper;
import org.dromara.hutool.json.writer.JSONWriter;
import org.dromara.hutool.json.writer.ValueWriter;
import org.dromara.hutool.json.writer.ValueWriterManager;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* JSON原始类型数据封装根据RFC8259规范JSONPrimitive只包含以下类型
@ -34,7 +37,7 @@ import java.lang.reflect.Type;
* @author Looly
* @since 6.0.0
*/
public class JSONPrimitive implements JSON {
public class JSONPrimitive implements Wrapper<Object>, JSON {
private static final long serialVersionUID = -2026215279191790345L;
private Object value;
@ -72,6 +75,11 @@ public class JSONPrimitive implements JSON {
return this.value;
}
@Override
public Object getRaw() {
return this.value;
}
/**
* 设置值
*
@ -99,6 +107,46 @@ public class JSONPrimitive implements JSON {
return this;
}
/**
* 是否为数字类型
*
* @return 是否为数字类型
*/
public boolean isNumber() {
return value instanceof Number;
}
/**
* 自增仅支持数字类型包括
* <ul>
* <li>{@link Integer}</li>
* <li>{@link Long}</li>
* <li>{@link Double}</li>
* <li>{@link Float}</li>
* <li>{@link BigInteger}</li>
* <li>{@link BigDecimal}</li>
* </ul>
*
* @throws JSONException 非数字类型
*/
public void increment(){
if (value instanceof BigInteger) {
value = ((BigInteger) value).add(BigInteger.ONE);
} else if (value instanceof BigDecimal) {
value = ((BigDecimal) value).add(BigDecimal.ONE);
} else if (value instanceof Integer) {
value = (Integer) value + 1;
} else if (value instanceof Long) {
value = (Long) value + 1;
} else if (value instanceof Double) {
value = (Double) value + 1;
} else if (value instanceof Float) {
value = (Float) value + 1;
} else {
throw new JSONException("Unable to increment {} type: {}", value, value.getClass());
}
}
@Override
public int size() {
return 1;

View File

@ -19,10 +19,12 @@ package org.dromara.hutool.json;
import org.dromara.hutool.core.io.IORuntimeException;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.lang.mutable.MutableEntry;
import org.dromara.hutool.core.reflect.TypeReference;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.json.convert.JSONConverter;
import org.dromara.hutool.json.mapper.JSONObjectMapper;
import org.dromara.hutool.json.writer.JSONWriter;
import org.dromara.hutool.json.writer.ValueWriter;
import org.dromara.hutool.json.writer.ValueWriterManager;
@ -34,6 +36,7 @@ import java.io.Writer;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.List;
import java.util.function.Predicate;
/**
* JSON工具类
@ -42,15 +45,14 @@ import java.util.List;
*/
public class JSONUtil {
// -------------------------------------------------------------------- Pause start
// region ----- of
/**
* 创建JSONObject
*
* @return JSONObject
*/
public static OldJSONObject ofObj() {
return new OldJSONObject();
public static JSONObject ofObj() {
return new JSONObject();
}
/**
@ -60,8 +62,8 @@ public class JSONUtil {
* @return JSONObject
* @since 5.2.5
*/
public static OldJSONObject ofObj(final JSONConfig config) {
return new OldJSONObject(config);
public static JSONObject ofObj(final JSONConfig config) {
return new JSONObject(config);
}
/**
@ -83,7 +85,9 @@ public class JSONUtil {
public static JSONArray ofArray(final JSONConfig config) {
return new JSONArray(config);
}
// endregion
// region ----- parse
/**
* JSON字符串转JSONObject对象<br>
* 此方法会忽略空值但是对JSON字符串不影响
@ -91,21 +95,8 @@ public class JSONUtil {
* @param obj Bean对象或者Map
* @return JSONObject
*/
public static OldJSONObject parseObj(final Object obj) {
return new OldJSONObject(obj);
}
/**
* JSON字符串转JSONObject对象<br>
* 此方法会忽略空值但是对JSON字符串不影响
*
* @param obj Bean对象或者Map
* @param config JSON配置
* @return JSONObject
* @since 5.3.1
*/
public static OldJSONObject parseObj(final Object obj, final JSONConfig config) {
return new OldJSONObject(obj, config);
public static JSONObject parseObj(final Object obj) {
return parseObj(obj, JSONConfig.of(), null);
}
/**
@ -116,8 +107,35 @@ public class JSONUtil {
* @return JSONObject
* @since 3.0.9
*/
public static OldJSONObject parseObj(final Object obj, final boolean ignoreNullValue) {
return new OldJSONObject(obj, JSONConfig.of().setIgnoreNullValue(ignoreNullValue));
public static JSONObject parseObj(final Object obj, final boolean ignoreNullValue) {
return parseObj(obj, JSONConfig.of().setIgnoreNullValue(ignoreNullValue));
}
/**
* JSON字符串转JSONObject对象<br>
* 此方法会忽略空值但是对JSON字符串不影响
*
* @param obj Bean对象或者Map
* @param config JSON配置
* @return JSONObject
*/
public static JSONObject parseObj(final Object obj, final JSONConfig config) {
return parseObj(obj, config, null);
}
/**
* JSON字符串转JSONObject对象<br>
* 此方法会忽略空值但是对JSON字符串不影响
*
* @param obj Bean对象或者Map
* @param config JSON配置
* @param predicate 键值对过滤编辑器可以通过实现此接口完成解析前对键值对的过滤和修改操作{@link Predicate#test(Object)}{@code true}保留
* @return JSONObject
*/
public static JSONObject parseObj(final Object obj, final JSONConfig config, final Predicate<MutableEntry<Object, Object>> predicate) {
final JSONObject jsonObject = new JSONObject(config);
JSONObjectMapper.of(obj, predicate).mapTo(jsonObject);
return jsonObject;
}
/**
@ -185,10 +203,10 @@ public class JSONUtil {
* @param xmlStr XML字符串
* @return JSONObject
*/
public static OldJSONObject parseFromXml(final String xmlStr) {
public static JSONObject parseFromXml(final String xmlStr) {
return JSONXMLUtil.toJSONObject(xmlStr);
}
// -------------------------------------------------------------------- Parse end
// endregion
// -------------------------------------------------------------------- Read start
@ -212,7 +230,7 @@ public class JSONUtil {
* @return JSONObject
* @throws IORuntimeException IO异常
*/
public static OldJSONObject readJSONObject(final File file, final Charset charset) throws IORuntimeException {
public static JSONObject readJSONObject(final File file, final Charset charset) throws IORuntimeException {
return FileUtil.read(file, charset, JSONUtil::parseObj);
}
@ -307,12 +325,13 @@ public class JSONUtil {
* @return JSONObject
* @since 4.0.8
*/
public static OldJSONObject xmlToJson(final String xml) {
public static JSONObject xmlToJson(final String xml) {
return JSONXMLUtil.toJSONObject(xml);
}
// -------------------------------------------------------------------- toString end
// -------------------------------------------------------------------- toBean start
/**
* 转为实体类对象
*
@ -479,8 +498,7 @@ public class JSONUtil {
* JSON对象是否为空以下情况返回true<br>
* <ul>
* <li>null</li>
* <li>{@link JSONArray#isEmpty()}</li>
* <li>{@link OldJSONObject#isEmpty()}</li>
* <li>{@link JSON#isEmpty()}</li>
* </ul>
*
* @param json JSONObject或JSONArray
@ -490,12 +508,7 @@ public class JSONUtil {
if (null == json) {
return true;
}
if (json instanceof OldJSONObject) {
return ((OldJSONObject) json).isEmpty();
} else if (json instanceof JSONArray) {
return ((JSONArray) json).isEmpty();
}
return false;
return json.isEmpty();
}
/**

View File

@ -1,496 +0,0 @@
/*
* Copyright (c) 2013-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;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.func.LambdaInfo;
import org.dromara.hutool.core.func.LambdaUtil;
import org.dromara.hutool.core.func.SerFunction;
import org.dromara.hutool.core.func.SerSupplier;
import org.dromara.hutool.core.lang.mutable.MutableEntry;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.map.MapWrapper;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.json.mapper.JSONObjectMapper;
import org.dromara.hutool.json.mapper.JSONValueMapper;
import org.dromara.hutool.json.writer.JSONWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.function.Predicate;
/**
* JSON对象<br>
* <br>
*
* <pre>
* json = new JSONObject().put(&quot;JSON&quot;, &quot;Hello, World!&quot;).toString();
* </pre>
*
* @author looly
*/
public class OldJSONObject extends MapWrapper<String, Object> implements JSON, JSONGetter<String> {
private static final long serialVersionUID = -330220388580734346L;
/**
* 默认初始大小
*/
public static final int DEFAULT_CAPACITY = MapUtil.DEFAULT_INITIAL_CAPACITY;
/**
* 配置项
*/
private JSONConfig config;
/**
* 对象转换和包装用于将Java对象和值转换为JSON值
*/
private JSONValueMapper valueMapper;
// -------------------------------------------------------------------------------------------------------------------- Constructor start
/**
* 构造初始容量为 {@link #DEFAULT_CAPACITY}KEY有序
*/
public OldJSONObject() {
this(JSONConfig.of());
}
/**
* 构造
*
* @param config JSON配置项
* @since 4.6.5
*/
public OldJSONObject(final JSONConfig config) {
this(DEFAULT_CAPACITY, config);
}
/**
* 构造
*
* @param capacity 初始大小
* @param config JSON配置项{@code null}则使用默认配置
* @since 4.1.19
*/
public OldJSONObject(final int capacity, final JSONConfig config) {
super(InternalJSONUtil.createRawMapOld(capacity, ObjUtil.defaultIfNull(config, JSONConfig.of())));
this.config = ObjUtil.defaultIfNull(config, JSONConfig.of());
this.valueMapper = JSONValueMapper.of(this.config);
}
/**
* 构建JSONObjectJavaBean默认忽略null值其它对象不忽略规则如下
* <ol>
* <li>value为Map将键值对加入JSON对象</li>
* <li>value为JSON字符串CharSequence使用JSONTokener解析</li>
* <li>value为JSONTokener直接解析</li>
* <li>value为普通JavaBean如果为普通的JavaBean调用其getters方法getXXX或者isXXX获得值加入到JSON对象
* 例如如果JavaBean对象中有个方法getName()值为"张三"获得的键值对为name: "张三"</li>
* </ol>
*
* @param source JavaBean或者Map对象或者String
*/
public OldJSONObject(final Object source) {
this(source, JSONConfig.of().setIgnoreNullValue(InternalJSONUtil.defaultIgnoreNullValue(source)));
}
/**
* 构建JSONObject规则如下
* <ol>
* <li>value为Map将键值对加入JSON对象</li>
* <li>value为JSON字符串CharSequence使用JSONTokener解析</li>
* <li>value为JSONTokener直接解析</li>
* <li>value为普通JavaBean如果为普通的JavaBean调用其getters方法getXXX或者isXXX获得值加入到JSON对象例如如果JavaBean对象中有个方法getName()值为"张三"获得的键值对为name: "张三"</li>
* </ol>
* <p>
* 如果给定值为Map将键值对加入JSON对象;<br>
* 如果为普通的JavaBean调用其getters方法getXXX或者isXXX获得值加入到JSON对象<br>
* 例如如果JavaBean对象中有个方法getName()值为"张三"获得的键值对为name: "张三"
*
* @param source JavaBean或者Map对象或者String
* @param config JSON配置文件{@code null}则使用默认配置
* @since 4.2.2
*/
public OldJSONObject(final Object source, final JSONConfig config) {
this(source, config, null);
}
/**
* 构建JSONObject规则如下
* <ol>
* <li>value为Map将键值对加入JSON对象</li>
* <li>value为JSON字符串CharSequence使用JSONTokener解析</li>
* <li>value为JSONTokener直接解析</li>
* <li>value为普通JavaBean如果为普通的JavaBean调用其getters方法getXXX或者isXXX获得值加入到JSON对象例如如果JavaBean对象中有个方法getName()值为"张三"获得的键值对为name: "张三"</li>
* </ol>
* <p>
* 如果给定值为Map将键值对加入JSON对象;<br>
* 如果为普通的JavaBean调用其getters方法getXXX或者isXXX获得值加入到JSON对象<br>
* 例如如果JavaBean对象中有个方法getName()值为"张三"获得的键值对为name: "张三"
*
* @param source JavaBean或者Map对象或者String
* @param config JSON配置文件{@code null}则使用默认配置
* @param predicate 键值对过滤编辑器可以通过实现此接口完成解析前对键值对的过滤和修改操作{@code null}表示不过滤{@link Predicate#test(Object)}{@code true}保留
* @since 5.8.0
*/
public OldJSONObject(final Object source, final JSONConfig config, final Predicate<MutableEntry<Object, Object>> predicate) {
this(DEFAULT_CAPACITY, config);
JSONObjectMapper.of(source, predicate).mapTo(this);
}
// -------------------------------------------------------------------------------------------------------------------- Constructor end
@Override
public JSONConfig config() {
return this.config;
}
/**
* 设置转为字符串时的日期格式默认为时间戳null值<br>
* 此方法设置的日期格式仅对转换为JSON字符串有效对解析JSON为bean无效
*
* @param format 格式null表示使用时间戳
* @return this
* @since 4.1.19
*/
public OldJSONObject setDateFormat(final String format) {
this.config.setDateFormat(format);
return this;
}
/**
* 将指定KEY列表的值组成新的JSONArray
*
* @param names KEY列表
* @return A JSONArray of values.
* @throws JSONException If any of the values are non-finite numbers.
*/
public JSONArray toJSONArray(final Collection<String> names) throws JSONException {
if (CollUtil.isEmpty(names)) {
return null;
}
final JSONArray ja = new JSONArray(this.config);
Object value;
for (final String name : names) {
value = this.get(name);
if (null != value) {
ja.set(value);
}
}
return ja;
}
@Override
public Object getObj(final String key, final Object defaultValue) {
return getOrDefault(key, defaultValue);
}
@Override
public Object get(final Object key) {
Object value = super.get(key);
if(value instanceof JSONPrimitive){
value = ((JSONPrimitive) value).getValue();
}
return value;
}
@Override
public Object getOrDefault(final Object key, final Object defaultValue) {
Object value = super.getOrDefault(key, defaultValue);
if(value instanceof JSONPrimitive){
value = ((JSONPrimitive) value).getValue();
}
return value;
}
/**
* 根据lambda的方法引用获取
*
* @param func 方法引用
* @param <P> 参数类型
* @param <T> 返回值类型
* @return 获取表达式对应属性和返回的对象
*/
public <P, T> T get(final SerFunction<P, T> func) {
final LambdaInfo lambdaInfo = LambdaUtil.resolve(func);
return get(lambdaInfo.getFieldName(), lambdaInfo.getReturnType());
}
/**
* PUT 键值对到JSONObject中在忽略null模式下如果值为{@code null}将此键移除
*
* @param key
* @param value 值对象. 可以是以下类型: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull.NULL.
* @return this.
* @throws JSONException 值是无穷数字抛出此异常
*/
@Override
public Object put(final String key, final Object value) throws JSONException {
return put(key, value, null, config().isCheckDuplicate());
}
/**
* 设置键值对到JSONObject中在忽略null模式下如果值为{@code null}将此键移除
*
* @param key
* @param value 值对象. 可以是以下类型: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull.NULL.
* @return this.
* @throws JSONException 值是无穷数字抛出此异常
*/
public OldJSONObject set(final String key, final Object value) throws JSONException {
set(key, value, null);
return this;
}
/**
* 通过lambda批量设置值<br>
* 实际使用时可以使用getXXX的方法引用来完成键值对的赋值
* <pre>
* User user = GenericBuilder.of(User::new).with(User::setUsername, "hutool").build();
* (new JSONObject()).setFields(user::getNickname, user::getUsername);
* </pre>
*
* @param fields lambda,不能为空
* @return this
*/
public OldJSONObject setFields(final SerSupplier<?>... fields) {
Arrays.stream(fields).forEach(f -> set(LambdaUtil.getFieldName(f), f.get()));
return this;
}
/**
* 一次性Put 键值对如果key已经存在抛出异常如果键值中有null值忽略
*
* @param key
* @param value 值对象可以是以下类型: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull.NULL.
* @param predicate 键值对过滤编辑器可以通过实现此接口完成解析前对键值对的过滤和修改操作{@code null}表示不过滤{@link Predicate#test(Object)}{@code true}保留
* @return this
* @throws JSONException 值是无穷数字键重复抛出异常
* @since 5.8.0
*/
public OldJSONObject set(final String key, final Object value, final Predicate<MutableEntry<Object, Object>> predicate) throws JSONException {
put(key, value, predicate, config().isCheckDuplicate());
return this;
}
/**
* 设置键值对到JSONObject中在忽略null模式下如果值为{@code null}将此键移除
*
* @param key
* @param value 值对象. 可以是以下类型: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull.NULL.
* @param predicate 键值对过滤编辑器可以通过实现此接口完成解析前对键值对的过滤和修改操作{@code null}表示不过滤{@link Predicate#test(Object)}{@code true}保留
* @param checkDuplicate 是否检查重复键如果为{@code true}则出现重复键时抛出{@link JSONException}异常
* @return this.
* @throws JSONException 值是无穷数字抛出此异常
* @since 5.8.0
*/
public OldJSONObject set(final String key, final Object value, final Predicate<MutableEntry<Object, Object>> predicate, final boolean checkDuplicate) throws JSONException {
put(key, value, predicate, checkDuplicate);
return this;
}
/**
* 在键和值都为非空的情况下put到JSONObject中
*
* @param key
* @param value 值对象可以是以下类型: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull.NULL.
* @return this.
* @throws JSONException 值是无穷数字
*/
public OldJSONObject setOpt(final String key, final Object value) throws JSONException {
if (key != null && value != null) {
this.set(key, value);
}
return this;
}
@Override
public void putAll(final Map<? extends String, ?> m) {
for (final Entry<? extends String, ?> entry : m.entrySet()) {
this.set(entry.getKey(), entry.getValue());
}
}
/**
* 追加值.
* <ul>
* <li>如果键值对不存在或对应值为{@code null}则value为单独值</li>
* <li>如果值是一个{@link JSONArray}追加之</li>
* <li>如果值是一个其他值则和旧值共同组合为一个{@link JSONArray}</li>
* </ul>
*
* @param key
* @param value
* @return this.
* @throws JSONException 如果给定键为{@code null}或者键对应的值存在且为非JSONArray
*/
public OldJSONObject append(final String key, final Object value) throws JSONException {
return append(key, value, null);
}
/**
* 追加值.
* <ul>
* <li>如果键值对不存在或对应值为{@code null}则value为单独值</li>
* <li>如果值是一个{@link JSONArray}追加之</li>
* <li>如果值是一个其他值则和旧值共同组合为一个{@link JSONArray}</li>
* </ul>
*
* @param key
* @param value
* @param predicate 键值对过滤编辑器可以通过实现此接口完成解析前对键值对的过滤和修改操作{@code null}表示不过滤{@link Predicate#test(Object)}{@code true}保留
* @return this.
* @throws JSONException 如果给定键为{@code null}或者键对应的值存在且为非JSONArray
* @since 6.0.0
*/
public OldJSONObject append(String key, Object value, final Predicate<MutableEntry<Object, Object>> predicate) throws JSONException {
// 添加前置过滤通过MutablePair实现过滤修改键值对等
if (null != predicate) {
final MutableEntry<Object, Object> pair = new MutableEntry<>(key, value);
if (predicate.test(pair)) {
// 使用修改后的键值对
key = (String) pair.getKey();
value = pair.getValue();
} else {
// 键值对被过滤
return this;
}
}
final Object object = this.getObj(key);
if (object == null) {
this.set(key, value);
} else if (object instanceof JSONArray) {
((JSONArray) object).set(value);
} else {
this.set(key, JSONUtil.ofArray(this.config).set(object).set(value));
}
return this;
}
/**
* 对值加一如果值不存在赋值1如果为数字类型做加一操作
*
* @param key A key string.
* @return this.
* @throws JSONException 如果存在值非Integer, Long, Double, Float.
*/
public OldJSONObject increment(final String key) throws JSONException {
final Object value = this.getObj(key);
if (value == null) {
this.set(key, 1);
} else if (value instanceof BigInteger) {
this.set(key, ((BigInteger) value).add(BigInteger.ONE));
} else if (value instanceof BigDecimal) {
this.set(key, ((BigDecimal) value).add(BigDecimal.ONE));
} else if (value instanceof Integer) {
this.set(key, (Integer) value + 1);
} else if (value instanceof Long) {
this.set(key, (Long) value + 1);
} else if (value instanceof Double) {
this.set(key, (Double) value + 1);
} else if (value instanceof Float) {
this.set(key, (Float) value + 1);
} else {
throw new JSONException("Unable to increment [" + InternalJSONUtil.quote(key) + "].");
}
return this;
}
/**
* 返回JSON字符串<br>
* 如果解析错误返回{@code null}
*
* @return JSON字符串
*/
@Override
public String toString() {
return this.toJSONString(0);
}
/**
* 返回JSON字符串<br>
* 支持过滤器即选择哪些字段或值不写出
*
* @param indentFactor 每层缩进空格数
* @param predicate 过滤器同时可以修改编辑键和值{@link Predicate#test(Object)}{@code true}保留
* @return JSON字符串
* @since 5.7.15
*/
public String toJSONString(final int indentFactor, final Predicate<MutableEntry<Object, Object>> predicate) {
final JSONWriter jsonWriter = JSONWriter.of(new StringBuilder(), indentFactor, 0, config).setPredicate(predicate);
write(jsonWriter);
return jsonWriter.toString();
}
@Override
public void write(final JSONWriter writer) throws JSONException {
final JSONWriter copyWriter = writer.copyOf();
copyWriter.beginObj();
this.forEach((key, value) -> copyWriter.writeField(new MutableEntry<>(key, value)));
copyWriter.end();
}
@Override
public OldJSONObject clone() throws CloneNotSupportedException {
final OldJSONObject clone = (OldJSONObject) super.clone();
clone.config = this.config;
clone.valueMapper = this.valueMapper;
return clone;
}
/**
* 设置键值对到JSONObject中在忽略null模式下如果值为{@code null}将此键移除
*
* @param key
* @param value 值对象. 可以是以下类型: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull.NULL.
* @param predicate 键值对过滤编辑器可以通过实现此接口完成解析前对键值对的过滤和修改操作{@code null}表示不过滤{@link Predicate#test(Object)}{@code true}保留
* @param checkDuplicate 是否检查重复键如果为{@code true}则出现重复键时抛出{@link JSONException}异常
* @return 旧值
* @throws JSONException 值是无穷数字抛出此异常
* @since 5.8.0
*/
private Object put(String key, Object value, final Predicate<MutableEntry<Object, Object>> predicate, final boolean checkDuplicate) throws JSONException {
if (null == key) {
return null;
}
// 添加前置过滤通过MutablePair实现过滤修改键值对等
if (null != predicate) {
final MutableEntry<Object, Object> pair = new MutableEntry<>(key, value);
if (predicate.test(pair)) {
// 使用修改后的键值对
key = (String) pair.getKey();
value = pair.getValue();
} else {
// 键值对被过滤
return null;
}
}
final boolean ignoreNullValue = this.config.isIgnoreNullValue();
if (null == value && ignoreNullValue) {
// 忽略值模式下如果值为空清除key
return this.remove(key);
} else if (checkDuplicate && containsKey(key)) {
throw new JSONException("Duplicate key \"{}\"", key);
}
return super.put(key, this.valueMapper.map(value));
}
}

View File

@ -33,7 +33,10 @@ import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.json.*;
import org.dromara.hutool.json.reader.JSONParser;
import org.dromara.hutool.json.reader.JSONTokener;
import org.dromara.hutool.json.serializer.*;
import org.dromara.hutool.json.serializer.JSONDeserializer;
import org.dromara.hutool.json.serializer.JSONSerializer;
import org.dromara.hutool.json.serializer.SerializerManager;
import org.dromara.hutool.json.serializer.SimpleJSONContext;
import java.io.Serializable;
import java.lang.reflect.Type;
@ -69,7 +72,7 @@ public class JSONConverter implements Converter, Serializable {
public static JSONConverter of(final JSONConfig config) {
final JSONConverter jsonConverter = new JSONConverter(config);
jsonConverter.registerConverter = new RegisterConverter(jsonConverter)
.register(OldJSONObject.class, INSTANCE)
.register(JSONObject.class, INSTANCE)
.register(JSONArray.class, INSTANCE)
.register(JSONPrimitive.class, INSTANCE);
jsonConverter.specialConverter = new SpecialConverter(jsonConverter);
@ -90,7 +93,7 @@ public class JSONConverter implements Converter, Serializable {
}
@Override
public Object convert(Type targetType, Object value) throws ConvertException {
public Object convert(Type targetType, final Object value) throws ConvertException {
if (null == value) {
return null;
}
@ -169,11 +172,11 @@ public class JSONConverter implements Converter, Serializable {
return toJSON((CharSequence) obj);
} else if (obj instanceof MapWrapper) {
// MapWrapper实现了Iterable会被当作JSONArray此处做修正
json = new OldJSONObject(obj, config);
json = JSONUtil.parseObj(obj, config);
} else if (obj instanceof Iterable || obj instanceof Iterator || ArrayUtil.isArray(obj)) {// 列表
json = new JSONArray(obj, config);
json = JSONUtil.parseArray(obj, config);
} else {// 对象
json = new OldJSONObject(obj, config);
json = JSONUtil.parseObj(obj, config);
}
return json;

View File

@ -21,7 +21,7 @@ import org.dromara.hutool.core.date.format.GlobalCustomFormat;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.json.JSONConfig;
import org.dromara.hutool.json.OldJSONObject;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import java.io.Serializable;
@ -40,7 +40,7 @@ public class Claims implements Serializable {
// 时间使用秒级时间戳表示
private final JSONConfig CONFIG = JSONConfig.of().setDateFormat(GlobalCustomFormat.FORMAT_SECONDS);
private OldJSONObject claimJSON;
private JSONObject claimJSON;
/**
* 增加Claims属性如果属性值为{@code null}则移除这个属性
@ -86,7 +86,7 @@ public class Claims implements Serializable {
*
* @return JSON字符串
*/
public OldJSONObject getClaimsJson() {
public JSONObject getClaimsJson() {
init();
return this.claimJSON;
}
@ -109,7 +109,7 @@ public class Claims implements Serializable {
private void init(){
if(null == this.claimJSON){
this.claimJSON = new OldJSONObject(CONFIG);
this.claimJSON = new JSONObject(CONFIG);
}
}
}

View File

@ -24,7 +24,7 @@ import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.text.split.SplitUtil;
import org.dromara.hutool.core.util.CharsetUtil;
import org.dromara.hutool.json.OldJSONObject;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.jwt.signers.AlgorithmUtil;
import org.dromara.hutool.json.jwt.signers.JWTSigner;
import org.dromara.hutool.json.jwt.signers.JWTSignerUtil;
@ -203,7 +203,7 @@ public class JWT implements RegisteredPayload<JWT> {
*
* @return 头信息
*/
public OldJSONObject getHeaders() {
public JSONObject getHeaders() {
return this.header.getClaimsJson();
}
@ -265,7 +265,7 @@ public class JWT implements RegisteredPayload<JWT> {
*
* @return 载荷信息
*/
public OldJSONObject getPayloads() {
public JSONObject getPayloads() {
return this.payload.getClaimsJson();
}

View File

@ -33,7 +33,7 @@ public class JWTUtil {
* @param key HS256(HmacSHA256)密钥
* @return JWT Token
*/
public static String createToken(final Map<String, Object> payload, final byte[] key) {
public static String createToken(final Map<String, ?> payload, final byte[] key) {
return createToken(MapUtil.of(JWTHeader.TYPE, "JWT"), payload, key);
}
@ -45,7 +45,7 @@ public class JWTUtil {
* @param key HS256(HmacSHA256)密钥
* @return JWT Token
*/
public static String createToken(final Map<String, Object> headers, final Map<String, Object> payload, final byte[] key) {
public static String createToken(final Map<String, ?> headers, final Map<String, ?> payload, final byte[] key) {
return JWT.of()
.addHeaders(headers)
.addPayloads(payload)

View File

@ -85,12 +85,12 @@ public class JSONObjectMapper {
}
/**
* 将给定对象转换为{@link OldJSONObject}
* 将给定对象转换为{@link JSONObject}
*
* @param jsonObject 目标{@link OldJSONObject}
* @param jsonObject 目标{@link JSONObject}
*/
@SuppressWarnings("rawtypes")
public void mapTo(final OldJSONObject jsonObject) {
public void mapTo(final JSONObject jsonObject) {
final Object source = this.source;
if (null == source) {
return;
@ -117,11 +117,11 @@ public class JSONObjectMapper {
} else if (source instanceof Map) {
// Map
for (final Map.Entry<?, ?> e : ((Map<?, ?>) source).entrySet()) {
jsonObject.set(ConvertUtil.toStr(e.getKey()), e.getValue(), predicate, false);
jsonObject.set(ConvertUtil.toStr(e.getKey()), e.getValue());
}
} else if (source instanceof Map.Entry) {
final Map.Entry entry = (Map.Entry) source;
jsonObject.set(ConvertUtil.toStr(entry.getKey()), entry.getValue(), predicate, false);
jsonObject.set(ConvertUtil.toStr(entry.getKey()), entry.getValue());
} else if (source instanceof CharSequence) {
// 可能为JSON字符串
mapFromStr((CharSequence) source, jsonObject);
@ -153,15 +153,14 @@ public class JSONObjectMapper {
* {@link ResourceBundle}转换
*
* @param bundle ResourceBundle
* @param jsonObject {@link OldJSONObject}
* @since 5.3.1
* @param jsonObject {@link JSONObject}
*/
private void mapFromResourceBundle(final ResourceBundle bundle, final OldJSONObject jsonObject) {
private void mapFromResourceBundle(final ResourceBundle bundle, final JSONObject jsonObject) {
final Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
final String key = keys.nextElement();
if (key != null) {
InternalJSONUtil.propertyPut(jsonObject, key, bundle.getString(key), this.predicate);
InternalJSONUtil.propertyPut(jsonObject, key, bundle.getString(key));
}
}
}
@ -170,9 +169,9 @@ public class JSONObjectMapper {
* 从字符串转换
*
* @param source JSON字符串
* @param jsonObject {@link OldJSONObject}
* @param jsonObject {@link JSONObject}
*/
private void mapFromStr(final CharSequence source, final OldJSONObject jsonObject) {
private void mapFromStr(final CharSequence source, final JSONObject jsonObject) {
final String jsonStr = StrUtil.trim(source);
if (StrUtil.startWith(jsonStr, '<')) {
// 可能为XML
@ -188,9 +187,9 @@ public class JSONObjectMapper {
*
* @param x JSONTokener
* @param config JSON配置
* @param jsonObject {@link OldJSONObject}
* @param jsonObject {@link JSONObject}
*/
private void mapFromTokener(final JSONTokener x, final JSONConfig config, final OldJSONObject jsonObject) {
private void mapFromTokener(final JSONTokener x, final JSONConfig config, final JSONObject jsonObject) {
JSONParser.of(x, config).setPredicate(this.predicate).parseTo(jsonObject);
}
@ -198,9 +197,9 @@ public class JSONObjectMapper {
* 从Record转换
*
* @param record Record对象
* @param jsonObject {@link OldJSONObject}
* @param jsonObject {@link JSONObject}
*/
private void mapFromRecord(final Object record, final OldJSONObject jsonObject) {
private void mapFromRecord(final Object record, final JSONObject jsonObject) {
final Map.Entry<String, Type>[] components = RecordUtil.getRecordComponents(record.getClass());
String key;
@ -214,9 +213,9 @@ public class JSONObjectMapper {
* 从Bean转换
*
* @param bean Bean对象
* @param jsonObject {@link OldJSONObject}
* @param jsonObject {@link JSONObject}
*/
private void mapFromBean(final Object bean, final OldJSONObject jsonObject) {
private void mapFromBean(final Object bean, final JSONObject jsonObject) {
final CopyOptions copyOptions = InternalJSONUtil.toCopyOptions(jsonObject.config());
if (null != this.predicate) {
copyOptions.setFieldEditor((entry -> this.predicate.test(

View File

@ -17,7 +17,7 @@
package org.dromara.hutool.json.mapper;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.core.exception.ExceptionUtil;
import org.dromara.hutool.json.*;
import org.dromara.hutool.json.writer.ValueWriterManager;
@ -77,33 +77,38 @@ public class JSONValueMapper implements Serializable {
* @param object 被映射的对象
* @return 映射后的值null表示此值需被忽略
*/
public Object map(final Object object) {
// nullJSON字符串和自定义对象原样存储
if (null == object
// 当用户自定义了对象的字符串表示形式则保留这个对象
|| null != ValueWriterManager.getInstance().get(object)
|| object instanceof JSON //
|| object instanceof CharSequence //
|| ObjUtil.isBasicType(object) //
) {
if(object instanceof JSONPrimitive){
return ((JSONPrimitive) object).getValue();
public JSON map(final Object object) {
if(null == object || object instanceof JSON){
return (JSON) object;
}
return object;
if(null != ValueWriterManager.getInstance().get(object)){
return new JSONPrimitive(object, jsonConfig);
}
// if (object instanceof CharSequence
// || ObjUtil.isBasicType(object)) {
// return new JSONPrimitive(object, jsonConfig);
// }
// 特定对象转换
try {
// JSONArray
if (object instanceof Iterable || ArrayUtil.isArray(object)) {
return new JSONArray(object, jsonConfig);
final JSONArray jsonArray = new JSONArray(jsonConfig);
JSONArrayMapper.of(object, null).mapTo(jsonArray);
return jsonArray;
}
// 默认按照JSONObject对待
return new OldJSONObject(object, jsonConfig);
final JSONObject jsonObject = new JSONObject(jsonConfig);
JSONObjectMapper.of(object, null).mapTo(jsonObject);
return jsonObject;
} catch (final Exception exception) {
if(jsonConfig.isIgnoreError()){
return null;
}
throw ExceptionUtil.wrap(exception, JSONException.class);
}
}
}

View File

@ -121,7 +121,7 @@ public class JSONParser {
}
switch (tokener.nextClean()) {
case CharUtil.DELIM_START:
nextTo((OldJSONObject) json);
nextTo((JSONObject) json);
break;
case CharUtil.BRACKET_START:
nextTo((JSONArray) json);
@ -146,7 +146,7 @@ public class JSONParser {
final JSON result;
switch (firstChar) {
case CharUtil.DELIM_START:
final OldJSONObject jsonObject = new OldJSONObject(config);
final JSONObject jsonObject = new JSONObject(config);
nextTo(jsonObject);
result = jsonObject;
break;
@ -167,7 +167,7 @@ public class JSONParser {
*
* @param jsonObject JSON对象
*/
private void nextTo(final OldJSONObject jsonObject) {
private void nextTo(final JSONObject jsonObject) {
final JSONTokener tokener = this.tokener;
char c;

View File

@ -17,7 +17,7 @@
package org.dromara.hutool.json.serializer;
import org.dromara.hutool.json.JSON;
import org.dromara.hutool.json.OldJSONObject;
import org.dromara.hutool.json.JSONObject;
/**
* 序列化接口通过实现此接口实现自定义的对象转换为JSON的操作
@ -33,7 +33,7 @@ public interface JSONSerializer<V> {
* <ul>
* <li>如果为原始类型可以转为{@link org.dromara.hutool.json.JSONPrimitive}</li>
* <li>如果是集合或数组类可以转为{@link org.dromara.hutool.json.JSONArray}</li>
* <li>如果是Bean或键值对类型可以转为{@link OldJSONObject}</li>
* <li>如果是Bean或键值对类型可以转为{@link JSONObject}</li>
* </ul>
*
* @param bean 指定类型对象

View File

@ -66,12 +66,12 @@ public class TemporalAccessorSerializer implements JSONSerializer<TemporalAccess
@Override
public JSON serialize(final TemporalAccessor bean, final JSONContext context) {
final OldJSONObject json;
final JSONObject json;
final JSON contextJson = context.getContextJson();
if(contextJson instanceof OldJSONObject){
json = (OldJSONObject) contextJson;
if(contextJson instanceof JSONObject){
json = (JSONObject) contextJson;
}else {
json = new OldJSONObject(7F / 0.75F + 1F, context.config());
json = new JSONObject((int) (7F / 0.75F + 1F), context.config());
}
if (bean instanceof LocalDate) {
final LocalDate localDate = (LocalDate) bean;
@ -112,7 +112,7 @@ public class TemporalAccessorSerializer implements JSONSerializer<TemporalAccess
// TODO JSONArray
// JSONObject
final OldJSONObject jsonObject = (OldJSONObject) json;
final JSONObject jsonObject = (JSONObject) json;
if (LocalDate.class.equals(this.temporalAccessorClass) || LocalDateTime.class.equals(this.temporalAccessorClass)) {
//
final Integer year = jsonObject.getInt(YEAR_KEY);

View File

@ -126,8 +126,8 @@ public class JSONWriter implements Appendable, Flushable, Closeable {
* @return JSONWriter
*/
@SuppressWarnings("resource")
public JSONWriter copyOf() {
return new JSONWriter(this.appendable, this.indentFactor, this.indent, this.config)
public JSONWriter copyOfSub() {
return new JSONWriter(this.appendable, this.indentFactor, this.indent + indentFactor, this.config)
.setPredicate(this.predicate);
}

View File

@ -22,7 +22,7 @@ import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.xml.XmlConstants;
import org.dromara.hutool.json.InternalJSONUtil;
import org.dromara.hutool.json.JSONException;
import org.dromara.hutool.json.OldJSONObject;
import org.dromara.hutool.json.JSONObject;
import java.util.function.Predicate;
@ -67,7 +67,7 @@ public class JSONXMLParser {
* @param jo JSONObject
* @throws JSONException 解析异常
*/
public void parseJSONObject(final String xmlStr, final OldJSONObject jo) throws JSONException {
public void parseJSONObject(final String xmlStr, final JSONObject jo) throws JSONException {
final XMLTokener x = new XMLTokener(xmlStr);
while (x.more() && x.skipPast("<")) {
parse(x, jo, null, 0);
@ -78,16 +78,16 @@ public class JSONXMLParser {
* 扫描XML内容并解析到JSONObject中
*
* @param x {@link XMLTokener}
* @param context {@link OldJSONObject}
* @param context {@link JSONObject}
* @param name 标签名null表示从根标签开始解析
* @param currentNestingDepth 当前层级
* @return {@code true}表示解析完成
* @throws JSONException JSON异常
*/
private boolean parse(final XMLTokener x, final OldJSONObject context, final String name, final int currentNestingDepth) throws JSONException {
private boolean parse(final XMLTokener x, final JSONObject context, final String name, final int currentNestingDepth) throws JSONException {
final char c;
int i;
final OldJSONObject jsonobject;
final JSONObject jsonobject;
String string;
final String tagName;
Object token;
@ -108,7 +108,7 @@ public class JSONXMLParser {
if (x.next() == '[') {
string = x.nextCDATA();
if (!string.isEmpty()) {
context.append("content", string);
append(context, "content", string);
}
return false;
}
@ -156,7 +156,7 @@ public class JSONXMLParser {
} else {
tagName = (String) token;
token = null;
jsonobject = new OldJSONObject();
jsonobject = new JSONObject();
final boolean keepStrings = parseConfig.isKeepStrings();
for (; ; ) {
if (token == null) {
@ -184,9 +184,9 @@ public class JSONXMLParser {
throw x.syntaxError("Misshaped tag");
}
if (!jsonobject.isEmpty()) {
context.append(tagName, jsonobject, this.predicate);
append(context, tagName, jsonobject);
} else {
context.append(tagName, StrUtil.EMPTY, this.predicate);
append(context, tagName, StrUtil.EMPTY);
}
return false;
@ -216,11 +216,11 @@ public class JSONXMLParser {
// Nested element
if (parse(x, jsonobject, tagName, currentNestingDepth + 1)) {
if (jsonobject.isEmpty()) {
context.append(tagName, StrUtil.EMPTY, this.predicate);
append(context, tagName, StrUtil.EMPTY);
} else if (jsonobject.size() == 1 && jsonobject.get("content") != null) {
context.append(tagName, jsonobject.get("content"), this.predicate);
append(context, tagName, jsonobject.get("content"));
} else {
context.append(tagName, jsonobject, this.predicate);
append(context, tagName, jsonobject);
}
return false;
}
@ -232,4 +232,24 @@ public class JSONXMLParser {
}
}
}
/**
* 添加键值对通过MutableEntry实现过滤修改键值对等
*
* @param jsonObject JSONObject
* @param key
* @param value
*/
private void append(final JSONObject jsonObject, String key, final Object value){
if (null != predicate) {
final MutableEntry<Object, Object> entry = new MutableEntry<>(key, value);
if (predicate.test(entry)) {
// 使用修改后的键值对
key = (String) entry.getKey();
jsonObject.append(key, entry.getValue());
}
}else {
jsonObject.append(key, value);
}
}
}

View File

@ -18,11 +18,11 @@ package org.dromara.hutool.json.xml;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.text.CharUtil;
import org.dromara.hutool.core.text.escape.EscapeUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.text.escape.EscapeUtil;
import org.dromara.hutool.json.JSONArray;
import org.dromara.hutool.json.JSONException;
import org.dromara.hutool.json.OldJSONObject;
import org.dromara.hutool.json.JSONObject;
/**
* JSON转XML字符串工具
@ -70,13 +70,13 @@ public class JSONXMLSerializer {
}
final StringBuilder sb = new StringBuilder();
if (object instanceof OldJSONObject) {
if (object instanceof JSONObject) {
// Emit <tagName>
appendTag(sb, tagName, false);
// Loop thru the keys.
((OldJSONObject) object).forEach((key, value) -> {
((JSONObject) object).forEach((key, value) -> {
if (ArrayUtil.isArray(value)) {
value = new JSONArray(value);
}

View File

@ -17,7 +17,7 @@
package org.dromara.hutool.json.xml;
import org.dromara.hutool.json.JSONException;
import org.dromara.hutool.json.OldJSONObject;
import org.dromara.hutool.json.JSONObject;
/**
* 提供静态方法在XML和JSONObject之间转换
@ -37,7 +37,7 @@ public class JSONXMLUtil {
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException Thrown if there is an errors while parsing the string
*/
public static OldJSONObject toJSONObject(final String string) throws JSONException {
public static JSONObject toJSONObject(final String string) throws JSONException {
return toJSONObject(string, ParseConfig.of());
}
@ -52,8 +52,8 @@ public class JSONXMLUtil {
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException Thrown if there is an errors while parsing the string
*/
public static OldJSONObject toJSONObject(final String string, final ParseConfig parseConfig) throws JSONException {
return toJSONObject(string, new OldJSONObject(), parseConfig);
public static JSONObject toJSONObject(final String string, final ParseConfig parseConfig) throws JSONException {
return toJSONObject(string, new JSONObject(), parseConfig);
}
/**
@ -67,7 +67,7 @@ public class JSONXMLUtil {
* @throws JSONException 解析异常
* @since 5.3.1
*/
public static OldJSONObject toJSONObject(final String xmlStr, final OldJSONObject jo, final ParseConfig parseConfig) throws JSONException {
public static JSONObject toJSONObject(final String xmlStr, final JSONObject jo, final ParseConfig parseConfig) throws JSONException {
JSONXMLParser.of(parseConfig, null).parseJSONObject(xmlStr, jo);
return jo;
}

View File

@ -32,7 +32,7 @@ public class CustomSerializeTest {
public void init() {
SerializerManager.getInstance().register(CustomBean.class,
(JSONSerializer<CustomBean>) (bean, context) ->
((OldJSONObject)context.getContextJson()).set("customName", bean.name));
((JSONObject)context.getContextJson()).set("customName", bean.name));
}
@Test
@ -40,7 +40,7 @@ public class CustomSerializeTest {
final CustomBean customBean = new CustomBean();
customBean.name = "testName";
final OldJSONObject obj = JSONUtil.parseObj(customBean);
final JSONObject obj = JSONUtil.parseObj(customBean);
Assertions.assertEquals("testName", obj.getStr("customName"));
}
@ -49,7 +49,7 @@ public class CustomSerializeTest {
final CustomBean customBean = new CustomBean();
customBean.name = "testName";
final OldJSONObject obj = JSONUtil.ofObj().set("customBean", customBean);
final JSONObject obj = JSONUtil.ofObj().set("customBean", customBean);
Assertions.assertEquals("testName", obj.getJSONObject("customBean").getStr("customName"));
}
@ -57,7 +57,7 @@ public class CustomSerializeTest {
public void deserializeTest() {
SerializerManager.getInstance().register(CustomBean.class, (JSONDeserializer<CustomBean>) (json, deserializeType) -> {
final CustomBean customBean = new CustomBean();
customBean.name = ((OldJSONObject) json).getStr("customName");
customBean.name = ((JSONObject) json).getStr("customName");
return customBean;
});

View File

@ -71,7 +71,7 @@ public class Issue1101Test {
"\t\"type\": 0\n" +
"}";
final OldJSONObject jsonObject = JSONUtil.parseObj(json);
final JSONObject jsonObject = JSONUtil.parseObj(json);
final TreeNode treeNode = JSONUtil.toBean(jsonObject, TreeNode.class);
Assertions.assertEquals(2, treeNode.getChildren().size());

View File

@ -30,7 +30,7 @@ public class Issue1200Test {
@Test
public void toBeanTest() {
final OldJSONObject jsonObject = JSONUtil.parseObj(
final JSONObject jsonObject = JSONUtil.parseObj(
ResourceUtil.readUtf8Str("issue1200.json"),
JSONConfig.of().setIgnoreError(true));

View File

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

View File

@ -35,7 +35,7 @@ public class Issue2090Test {
final TestBean test = new TestBean();
test.setLocalDate(LocalDate.now());
final OldJSONObject json = JSONUtil.parseObj(test);
final JSONObject json = JSONUtil.parseObj(test);
final TestBean test1 = json.toBean(TestBean.class);
Assertions.assertEquals(test, test1);
}
@ -43,14 +43,14 @@ public class Issue2090Test {
@Test
public void parseLocalDateTest(){
final LocalDate localDate = LocalDate.now();
final OldJSONObject jsonObject = JSONUtil.parseObj(localDate);
final JSONObject jsonObject = JSONUtil.parseObj(localDate);
Assertions.assertNotNull(jsonObject.toString());
}
@Test
public void toBeanLocalDateTest(){
final LocalDate d = LocalDate.now();
final OldJSONObject obj = JSONUtil.parseObj(d);
final JSONObject obj = JSONUtil.parseObj(d);
final LocalDate d2 = obj.toBean(LocalDate.class);
Assertions.assertEquals(d, d2);
}
@ -58,7 +58,7 @@ public class Issue2090Test {
@Test
public void toBeanLocalDateTimeTest(){
final LocalDateTime d = LocalDateTime.now();
final OldJSONObject obj = JSONUtil.parseObj(d);
final JSONObject obj = JSONUtil.parseObj(d);
final LocalDateTime d2 = obj.toBean(LocalDateTime.class);
Assertions.assertEquals(d, d2);
}
@ -66,14 +66,14 @@ public class Issue2090Test {
@Test
public void toBeanLocalTimeTest(){
final LocalTime d = LocalTime.now();
final OldJSONObject obj = JSONUtil.parseObj(d);
final JSONObject obj = JSONUtil.parseObj(d);
final LocalTime d2 = obj.toBean(LocalTime.class);
Assertions.assertEquals(d, d2);
}
@Test
public void monthTest(){
final OldJSONObject jsonObject = new OldJSONObject();
final JSONObject jsonObject = new JSONObject();
jsonObject.set("month", Month.JANUARY);
Assertions.assertEquals("{\"month\":1}", jsonObject.toString());
}

View File

@ -42,7 +42,7 @@ public class Issue2131Test {
Stream.of(apple, pear).forEach(collections::add);
final String jsonStr = JSONUtil.toJsonStr(goodsResponse);
final OldJSONObject jsonObject = JSONUtil.parseObj(jsonStr);
final JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
final GoodsResponse result = jsonObject.toBean(GoodsResponse.class);
Assertions.assertEquals(0, result.getCollections().size());

View File

@ -25,7 +25,7 @@ public class Issue2507Test {
@Test
public void xmlToJsonTest(){
final String xml = "<MsgInfo> <Msg> <![CDATA[<msg><body><row action=\"select\"><DIET>低盐饮食[嘱托]]><![CDATA[]</DIET></row></body></msg>]]> </Msg> <Msg> <![CDATA[<msg><body><row action=\"select\"><DIET>流质饮食</DIET></row></body></msg>]]> </Msg> </MsgInfo>";
final OldJSONObject jsonObject = JSONUtil.xmlToJson(xml);
final JSONObject jsonObject = JSONUtil.xmlToJson(xml);
assertEquals("{\"MsgInfo\":{\"Msg\":[\"<msg><body><row action=\\\"select\\\"><DIET>低盐饮食[嘱托\",\"]</DIET></row></body></msg>\",\"<msg><body><row action=\\\"select\\\"><DIET>流质饮食</DIET></row></body></msg>\"]}}"
, jsonObject.toString());

View File

@ -57,7 +57,7 @@ public class Issue2555Test {
public static class MySerializer implements JSONSerializer<MyType> {
@Override
public JSON serialize(final MyType bean, final JSONContext context) {
return ((OldJSONObject)context.getContextJson()).set("addr", bean.getAddress());
return ((JSONObject)context.getContextJson()).set("addr", bean.getAddress());
}
}
@ -65,7 +65,7 @@ public class Issue2555Test {
@Override
public MyType deserialize(final JSON json, final Type deserializeType) {
final MyType myType = new MyType();
myType.setAddress(((OldJSONObject)json).getStr("addr"));
myType.setAddress(((JSONObject)json).getStr("addr"));
return myType;
}
}

View File

@ -32,7 +32,7 @@ public class Issue2572Test {
public void putDayOfWeekTest(){
final Set<DayOfWeek> weeks = new HashSet<>();
weeks.add(DayOfWeek.MONDAY);
final OldJSONObject obj = new OldJSONObject();
final JSONObject obj = new JSONObject();
obj.set("weeks", weeks);
Assertions.assertEquals("{\"weeks\":[1]}", obj.toString());
@ -45,7 +45,7 @@ public class Issue2572Test {
public void putMonthTest(){
final Set<Month> months = new HashSet<>();
months.add(Month.DECEMBER);
final OldJSONObject obj = new OldJSONObject();
final JSONObject obj = new JSONObject();
obj.set("months", months);
Assertions.assertEquals("{\"months\":[12]}", obj.toString());
@ -58,7 +58,7 @@ public class Issue2572Test {
public void putMonthDayTest(){
final Set<MonthDay> monthDays = new HashSet<>();
monthDays.add(MonthDay.of(Month.DECEMBER, 1));
final OldJSONObject obj = new OldJSONObject();
final JSONObject obj = new JSONObject();
obj.set("monthDays", monthDays);
Assertions.assertEquals("{\"monthDays\":[\"--12-01\"]}", obj.toString());

View File

@ -43,7 +43,7 @@ public class Issue2749Test {
final String jsonStr = JSONUtil.toJsonStr(map);
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
final OldJSONObject jsonObject = new OldJSONObject(jsonStr);
final JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
Assertions.assertNotNull(jsonObject);
// 栈溢出

View File

@ -22,7 +22,7 @@ import org.junit.jupiter.api.Test;
public class Issue2801Test {
@Test
public void toStringTest() {
final OldJSONObject recordObj = new OldJSONObject(JSONConfig.of().setIgnoreNullValue(false));
final JSONObject recordObj = new JSONObject(JSONConfig.of().setIgnoreNullValue(false));
recordObj.put("m_reportId", null);
Assertions.assertEquals("{\"m_reportId\":null}", recordObj.toString());
}

View File

@ -23,7 +23,7 @@ public class Issue2953Test {
@Test
public void parseObjWithBigNumberTest() {
final String a = "{\"a\": 114793903847679990000000000000000000000}";
final OldJSONObject jsonObject = JSONUtil.parseObj(a, JSONConfig.of());
final JSONObject jsonObject = JSONUtil.parseObj(a, JSONConfig.of());
Assertions.assertEquals("{\"a\":\"114793903847679990000000000000000000000\"}", jsonObject.toString());
}
}

View File

@ -24,7 +24,7 @@ public class Issue3051Test {
@Test
public void parseTest() {
final OldJSONObject jsonObject = JSONUtil.parseObj(new EmptyBean(),
final JSONObject jsonObject = JSONUtil.parseObj(new EmptyBean(),
JSONConfig.of().setIgnoreError(true));
Assertions.assertEquals("{}", jsonObject.toString());
@ -33,7 +33,7 @@ public class Issue3051Test {
@Test
public void parseTest2() {
Assertions.assertThrows(JSONException.class, ()->{
final OldJSONObject jsonObject = JSONUtil.parseObj(new EmptyBean());
final JSONObject jsonObject = JSONUtil.parseObj(new EmptyBean());
Assertions.assertEquals("{}", jsonObject.toString());
});
}

View File

@ -70,9 +70,9 @@ 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());
OldJSONObject contextJson = (OldJSONObject) context.getContextJson();
JSONObject contextJson = (JSONObject) context.getContextJson();
if(null == contextJson){
contextJson = new OldJSONObject(context.config());
contextJson = new JSONObject(context.config());
}
contextJson.set("authorities",strings);
return contextJson;

View File

@ -33,7 +33,7 @@ public class Issue3139Test {
" </c>\n" +
"</r>";
final OldJSONObject jsonObject = XmlUtil.xmlToBean(XmlUtil.parseXml(xml).getDocumentElement(), OldJSONObject.class);
final JSONObject jsonObject = XmlUtil.xmlToBean(XmlUtil.parseXml(xml).getDocumentElement(), JSONObject.class);
final R bean = jsonObject.toBean(R.class);
Assertions.assertNotNull(bean);

View File

@ -23,7 +23,7 @@ public class Issue3193Test {
@Test
void parseTest() {
final String jsonStr = "{\"desc\":\"测试数据\\\\\"}";
final OldJSONObject parse = JSONUtil.parseObj(jsonStr);
final JSONObject parse = JSONUtil.parseObj(jsonStr);
Assertions.assertEquals("测试数据\\", parse.getStr("desc"));
}
}

View File

@ -24,7 +24,7 @@ import org.junit.jupiter.api.Test;
public class Issue3274Test {
@Test
public void toBeanTest() {
final OldJSONObject entries = new OldJSONObject("{\n" +
final JSONObject entries = JSONUtil.parseObj("{\n" +
" \n" +
" \"age\": 36,\n" +
" \"gender\": \"\",\n" +

View File

@ -24,7 +24,7 @@ public class Issue3619Test {
public void parseObjTest() {
final String json = "{\"@timestamp\":\"2024-06-14T00:02:06.438Z\",\"@version\":\"1\",\"int_arr\":[-4]}";
final JSONConfig jsonConfig = JSONConfig.of().setKeyComparator(String.CASE_INSENSITIVE_ORDER);
final OldJSONObject jsonObject = JSONUtil.parseObj(json, jsonConfig);
final JSONObject jsonObject = JSONUtil.parseObj(json, jsonConfig);
final String jsonStr = jsonObject.toJSONString(0, pair -> {
final Object key = pair.getKey();

View File

@ -33,7 +33,7 @@ public class Issue644Test {
final BeanWithDate beanWithDate = new BeanWithDate();
beanWithDate.setDate(LocalDateTime.now());
final OldJSONObject jsonObject = JSONUtil.parseObj(beanWithDate);
final JSONObject jsonObject = JSONUtil.parseObj(beanWithDate);
BeanWithDate beanWithDate2 = JSONUtil.toBean(jsonObject, BeanWithDate.class);
Assertions.assertEquals(TimeUtil.formatNormal(beanWithDate.getDate()),

View File

@ -25,7 +25,7 @@ public class IssueI3EGJPTest {
@Test
public void hutoolMapToBean() {
final OldJSONObject paramJson = new OldJSONObject();
final JSONObject paramJson = new JSONObject();
paramJson.set("is_booleana", "1");
paramJson.set("is_booleanb", true);
final ConvertDO convertDO = BeanUtil.toBean(paramJson, ConvertDO.class);

View File

@ -28,7 +28,7 @@ public class IssueI4RBZ4Test {
public void sortTest(){
final String jsonStr = "{\"id\":\"123\",\"array\":[1,2,3],\"outNum\":356,\"body\":{\"ava1\":\"20220108\",\"use\":1,\"ava2\":\"20230108\"},\"name\":\"John\"}";
final OldJSONObject jsonObject = JSONUtil.parseObj(jsonStr, JSONConfig.of().setNatureKeyComparator());
final JSONObject jsonObject = JSONUtil.parseObj(jsonStr, JSONConfig.of().setNatureKeyComparator());
Assertions.assertEquals("{\"array\":[1,2,3],\"body\":{\"ava1\":\"20220108\",\"ava2\":\"20230108\",\"use\":1},\"id\":\"123\",\"name\":\"John\",\"outNum\":356}", jsonObject.toString());
}
}

View File

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

View File

@ -34,7 +34,7 @@ public class IssueI5DHK2Test {
" }]\n" +
"}";
final OldJSONObject json = JSONUtil.parseObj(jsonStr);
final JSONObject json = JSONUtil.parseObj(jsonStr);
final String exployerName = json
.getJSONArray("punished_parties")
.getJSONObject(0)

View File

@ -18,6 +18,7 @@ package org.dromara.hutool.json;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.io.resource.ResourceUtil;
import org.dromara.hutool.core.lang.Console;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -28,7 +29,8 @@ public class IssueI5OMSCTest {
@Test
public void filterTest(){
final OldJSONObject json = JSONUtil.parseObj(ResourceUtil.readUtf8Str("issueI5OMSC.json"));
final JSONObject json = JSONUtil.parseObj(ResourceUtil.readUtf8Str("issueI5OMSC.json"));
Console.log(json.toStringPretty());
final String s = json.toJSONString(0, (entry) -> {
final Object key = entry.getKey();

View File

@ -28,7 +28,7 @@ import javax.xml.xpath.XPathConstants;
public class IssueI676ITTest {
@Test
public void parseXMLTest() {
final OldJSONObject jsonObject = JSONUtil.parseObj(ResourceUtil.readUtf8Str("issueI676IT.json"));
final JSONObject jsonObject = JSONUtil.parseObj(ResourceUtil.readUtf8Str("issueI676IT.json"));
final String xmlStr = JSONXMLSerializer.toXml(jsonObject, null, (String) null);
final String content = String.valueOf(XPathUtil.getByXPath("/page/orderItems[1]/content", XmlUtil.readXml(xmlStr), XPathConstants.STRING));
Assertions.assertEquals(content, "bar1");

View File

@ -25,12 +25,11 @@ import java.util.AbstractMap;
public class IssueI6SZYBTest {
@SuppressWarnings("unchecked")
@Test
void mutableEntryTest() {
final MutableEntry<String, String> entry = MutableEntry.of("a", "b");
final String jsonStr = JSONUtil.toJsonStr(entry);
final MutableEntry<String, String> entry2 = JSONUtil.toBean(jsonStr, MutableEntry.class);
final MutableEntry<String, String> entry2 = JSONUtil.toBean(jsonStr, new TypeReference<MutableEntry<String, String>>() {});
Assertions.assertEquals(entry, entry2);
}
@ -45,22 +44,21 @@ public class IssueI6SZYBTest {
Assertions.assertEquals(entry, entry2);
}
@SuppressWarnings("unchecked")
@Test
void simpleEntryTest() {
final AbstractMap.SimpleEntry<String, String> entry = new AbstractMap.SimpleEntry<>("a", "b");
final String jsonStr = JSONUtil.toJsonStr(entry);
final AbstractMap.SimpleEntry<String, String> entry2 = JSONUtil.toBean(jsonStr, AbstractMap.SimpleEntry.class);
final AbstractMap.SimpleEntry<String, String> entry2 = JSONUtil.toBean(jsonStr, new TypeReference<AbstractMap.SimpleEntry<String, String>>() {});
Assertions.assertEquals(entry, entry2);
}
@SuppressWarnings("unchecked")
@Test
void simpleEntryTest2() {
final AbstractMap.SimpleEntry<String, String> entry = new AbstractMap.SimpleEntry<>("a", "b");
final String jsonStr = JSONUtil.toJsonStr(entry);
final MutableEntry<String, String> entry2 = JSONUtil.toBean(jsonStr, MutableEntry.class);
final MutableEntry<String, String> entry2 = JSONUtil.toBean(jsonStr, new TypeReference<MutableEntry<String, String>>() {});
Assertions.assertEquals(entry, entry2);
}

View File

@ -30,7 +30,7 @@ public class IssueI6YN2ATest {
public void toBeanTest() {
final String str = "{\"conditions\":{\"user\":\"test\",\"sex\":\"\"}," +
"\"headers\":{\"name\":\"姓名\",\"age\":\"年龄\",\"email\":\"邮箱\",\"number\":\"号码\",\"pwd\":\"密码\"}}";
final OldJSONObject jsonObject = JSONUtil.parseObj(str);
final JSONObject jsonObject = JSONUtil.parseObj(str);
final PageQuery<User> bean = jsonObject.toBean(new TypeReference<PageQuery<User>>() {});
Assertions.assertEquals("{name=姓名, age=年龄, email=邮箱, number=号码, pwd=密码}", bean.headers.toString());

View File

@ -26,7 +26,7 @@ public class IssueI76CSUTest {
@Test
void parseTest() {
final String str = "{ \"card\": true, \"content\": \"【标题】\n摘要\", \"time\": 1678434181000}";
final OldJSONObject entries = JSONUtil.parseObj(str);
final JSONObject entries = JSONUtil.parseObj(str);
Assertions.assertEquals("【标题】\n摘要", entries.getStr("content"));
}
}

View File

@ -33,8 +33,8 @@ public class IssueI7VM64Test {
final HashMap<String, Object> map = new HashMap<>();
map.put("a", "1");
final OldJSONObject jsonObject = new OldJSONObject();
jsonObject.put("c", map);
final JSONObject jsonObject = new JSONObject();
jsonObject.set("c", map);
map.put("b", 2);
//Console.log("Hutool JSON: " + jsonObject);

View File

@ -30,7 +30,7 @@ public class IssueI90ADXTest {
final TestBean testBean = new TestBean();
testBean.name = "aaaa";
final OldJSONObject json = JSONUtil.parseObj(testBean);
final JSONObject json = JSONUtil.parseObj(testBean);
Assertions.assertEquals("{\"name\":\"aaaa\"}", json.toString());
}

View File

@ -17,6 +17,7 @@
package org.dromara.hutool.json;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.json.mapper.JSONObjectMapper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -26,10 +27,12 @@ public class IssueI9DX5HTest {
@Test
void xmlToJSONTest() {
final String xml = "<GoodMsg>你好</GoodMsg>";
final OldJSONObject jsonObject = new OldJSONObject(xml, JSONConfig.of(), entry -> {
final JSONObjectMapper mapper = JSONObjectMapper.of(xml, entry -> {
entry.setKey(StrUtil.toUnderlineCase((CharSequence) entry.getKey()));
return true;
});
final JSONObject jsonObject = new JSONObject();
mapper.mapTo(jsonObject);
Assertions.assertEquals("{\"good_msg\":\"你好\"}", jsonObject.toString());
}

View File

@ -31,7 +31,7 @@ public class IssueI9HQQETest {
final JSONConfig jsonConfig = new JSONConfig();
jsonConfig.setDateFormat("dd/MM/yyyy");
final OldJSONObject entries = JSONUtil.parseObj(json, jsonConfig);
final JSONObject entries = JSONUtil.parseObj(json, jsonConfig);
final MMHBo mmh = entries.toBean(MMHBo.class);
Assertions.assertNotNull(mmh.getCurrentDate());

View File

@ -23,7 +23,7 @@ public class IssueIAP4GMTest {
@Test
void parse() {
final String res = "{\"uid\":\"asdf\\n\"}";
final OldJSONObject entries = JSONUtil.parseObj(res);
final JSONObject entries = JSONUtil.parseObj(res);
Assertions.assertEquals("asdf\n", entries.getStr("uid"));
}
}

View File

@ -33,7 +33,7 @@ public class IssuesI44E4HTest {
public void deserializerTest(){
SerializerManager.getInstance().register(TestDto.class, (JSONDeserializer<TestDto>) (json, deserializeType) -> {
final TestDto testDto = new TestDto();
testDto.setMd(new AcBizModuleMd("name1", ((OldJSONObject)json).getStr("md")));
testDto.setMd(new AcBizModuleMd("name1", ((JSONObject)json).getStr("md")));
return testDto;
});

View File

@ -17,20 +17,21 @@
package org.dromara.hutool.json;
import org.dromara.hutool.core.reflect.TypeReference;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class IssuesI4V14NTest {
@Test
public void parseTest(){
final String str = "{\"A\" : \"A\\nb\"}";
final OldJSONObject jsonObject = JSONUtil.parseObj(str);
Assertions.assertEquals("A\nb", jsonObject.getStr("A"));
final JSONObject jsonObject = JSONUtil.parseObj(str);
assertEquals("A\nb", jsonObject.getStr("A"));
final Map<String, String> map = jsonObject.toBean(new TypeReference<Map<String, String>>() {});
Assertions.assertEquals("A\nb", map.get("A"));
assertEquals("A\nb", map.get("A"));
}
}

View File

@ -46,7 +46,7 @@ public class JSONArrayTest {
@Test()
public void createJSONArrayFromJSONObjectTest() {
// JSONObject实现了Iterable接口可以转换为JSONArray
final OldJSONObject jsonObject = new OldJSONObject();
final JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray(jsonObject, JSONConfig.of());
assertEquals(new JSONArray(), jsonArray);
@ -99,7 +99,7 @@ public class JSONArrayTest {
public void readJSONArrayFromFileTest() {
final JSONArray array = JSONUtil.readJSONArray(FileUtil.file("exam_test.json"), CharsetUtil.UTF_8);
final OldJSONObject obj0 = array.getJSONObject(0);
final JSONObject obj0 = array.getJSONObject(0);
final Exam exam = JSONUtil.toBean(obj0, Exam.class);
assertEquals("0", exam.getAnswerArray()[0].getSeq());
}
@ -318,7 +318,7 @@ public class JSONArrayTest {
//noinspection MismatchedQueryAndUpdateOfCollection
final JSONArray array = new JSONArray(jsonArr, null, (mutable) -> {
if(mutable.getKey() instanceof Integer){
final OldJSONObject o = (OldJSONObject) mutable.getValue();
final JSONObject o = (JSONObject) mutable.getValue();
if ("111".equals(o.getStr("id"))) {
o.set("name", "test1_edit");
}
@ -327,7 +327,7 @@ public class JSONArrayTest {
});
assertEquals(2, array.size());
assertTrue(array.getJSONObject(0).containsKey("id"));
assertEquals("test1_edit", array.getJSONObject(0).get("name"));
assertEquals("test1_edit", array.getJSONObject(0).getObj("name"));
}
@Test
@ -337,8 +337,8 @@ public class JSONArrayTest {
array.add(JSONUtil.ofObj().set("name", "bbb"));
array.add(JSONUtil.ofObj().set("name", "ccc"));
StringBuilder result = new StringBuilder();
array.jsonIter(OldJSONObject.class).forEach(result::append);
final StringBuilder result = new StringBuilder();
array.jsonIter(JSONObject.class).forEach(result::append);
assertEquals("{\"name\":\"aaa\"}{\"name\":\"bbb\"}{\"name\":\"ccc\"}", result.toString());
}
}

View File

@ -70,10 +70,10 @@ public class JSONConvertTest {
tempMap.put("userInfoDict", userInfoDict);
tempMap.put("toSendManIdCard", 1);
final OldJSONObject obj = JSONUtil.parseObj(tempMap);
final JSONObject obj = JSONUtil.parseObj(tempMap);
Assertions.assertEquals(new Integer(1), obj.getInt("toSendManIdCard"));
final OldJSONObject examInfoDictsJson = obj.getJSONObject("userInfoDict");
final JSONObject examInfoDictsJson = obj.getJSONObject("userInfoDict");
Assertions.assertEquals(new Integer(1), examInfoDictsJson.getInt("id"));
Assertions.assertEquals("质量过关", examInfoDictsJson.getStr("realName"));
@ -90,7 +90,7 @@ public class JSONConvertTest {
+ " {\n" + " \"id\": 3,\n" + " \"answerIs\": 0,\n" + " \"examType\": 1\n" + " }\n" + " ],\n" //
+ " \"photoPath\": \"yx.mm.com\"\n" + " },\n" + " \"toSendManIdCard\": 1\n" + "}";
final OldJSONObject jsonObject = JSONUtil.parseObj(examJson).getJSONObject("examInfoDicts");
final JSONObject jsonObject = JSONUtil.parseObj(examJson).getJSONObject("examInfoDicts");
final UserInfoDict userInfoDict = jsonObject.toBean(UserInfoDict.class);
Assertions.assertEquals(userInfoDict.getId(), new Integer(1));
@ -99,7 +99,7 @@ public class JSONConvertTest {
//============
final String jsonStr = "{\"id\":null,\"examInfoDict\":[{\"answerIs\":1, \"id\":null}]}";//JSONUtil.toJsonStr(userInfoDict1);
final OldJSONObject jsonObject2 = JSONUtil.parseObj(jsonStr);//.getJSONObject("examInfoDicts");
final JSONObject jsonObject2 = JSONUtil.parseObj(jsonStr);//.getJSONObject("examInfoDicts");
final UserInfoDict userInfoDict2 = jsonObject2.toBean(UserInfoDict.class);
Assertions.assertNull(userInfoDict2.getId());
}
@ -110,7 +110,7 @@ public class JSONConvertTest {
@Test
public void testJson2Bean2() {
final String jsonStr = ResourceUtil.readUtf8Str("evaluation.json");
final OldJSONObject obj = JSONUtil.parseObj(jsonStr);
final JSONObject obj = JSONUtil.parseObj(jsonStr);
final PerfectEvaluationProductResVo vo = obj.toBean(PerfectEvaluationProductResVo.class);
Assertions.assertEquals(obj.getStr("HA001"), vo.getHA001());

View File

@ -42,7 +42,7 @@ public class JSONDeserializerTest {
@Override
public TestBean deserialize(final JSON json, final Type deserializeType) {
final OldJSONObject valueObj = (OldJSONObject) json;
final JSONObject valueObj = (JSONObject) json;
this.name = valueObj.getStr("customName");
this.address = valueObj.getStr("customAddress");
return this;

View File

@ -23,7 +23,7 @@ public class JSONNullTest {
@Test
public void parseNullTest(){
final OldJSONObject bodyjson = JSONUtil.parseObj("{\n" +
final JSONObject bodyjson = JSONUtil.parseObj("{\n" +
" \"device_model\": null,\n" +
" \"device_status_date\": null,\n" +
" \"imsi\": null,\n" +
@ -38,7 +38,7 @@ public class JSONNullTest {
@Test
public void parseNullTest2(){
final OldJSONObject bodyjson = JSONUtil.parseObj("{\n" +
final JSONObject bodyjson = JSONUtil.parseObj("{\n" +
" \"device_model\": null,\n" +
" \"device_status_date\": null,\n" +
" \"imsi\": null,\n" +

View File

@ -51,7 +51,7 @@ public class JSONObjectTest {
public void toStringTest() {
final String str = "{\"code\": 500, \"data\":null}";
//noinspection MismatchedQueryAndUpdateOfCollection
final OldJSONObject jsonObject = new OldJSONObject(str);
final JSONObject jsonObject = JSONUtil.parseObj(str, JSONConfig.of().setIgnoreNullValue(false));
Assertions.assertEquals("{\"code\":500,\"data\":null}", jsonObject.toString());
jsonObject.config().setIgnoreNullValue(true);
Assertions.assertEquals("{\"code\":500}", jsonObject.toString());
@ -61,7 +61,7 @@ public class JSONObjectTest {
public void toStringTest2() {
final String str = "{\"test\":\"关于开展2018年度“文明集体”、“文明职工”评选表彰活动的通知\"}";
//noinspection MismatchedQueryAndUpdateOfCollection
final OldJSONObject json = new OldJSONObject(str);
final JSONObject json = JSONUtil.parseObj(str);
Assertions.assertEquals(str, json.toString());
}
@ -70,51 +70,51 @@ public class JSONObjectTest {
*/
@Test
public void toStringTest3() {
final OldJSONObject json = Objects.requireNonNull(JSONUtil.ofObj()//
.set("dateTime", DateUtil.parse("2019-05-02 22:12:01")))//
.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"));
Assertions.assertEquals("{\"dateTime\":\"2019-05-02\"}", json.toString());
}
@Test
public void toStringWithDateTest() {
OldJSONObject json = JSONUtil.ofObj().set("date", DateUtil.parse("2019-05-08 19:18:21"));
JSONObject json = JSONUtil.ofObj().set("date", DateUtil.parse("2019-05-08 19:18:21"));
assert json != null;
Assertions.assertEquals("{\"date\":1557314301000}", json.toString());
json = Objects.requireNonNull(JSONUtil.ofObj().set("date", DateUtil.parse("2019-05-08 19:18:21"))).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"));
Assertions.assertEquals("{\"date\":\"2019-05-08\"}", json.toString());
}
@Test
public void putAllTest() {
final OldJSONObject json1 = JSONUtil.ofObj()
final JSONObject json1 = JSONUtil.ofObj()
.set("a", "value1")
.set("b", "value2")
.set("c", "value3")
.set("d", true);
final OldJSONObject json2 = JSONUtil.ofObj()
final JSONObject json2 = JSONUtil.ofObj()
.set("a", "value21")
.set("b", "value22");
// putAll操作会覆盖相同key的值因此a,b两个key的值改变c的值不变
json1.putAll(json2);
Assertions.assertEquals(json1.get("a"), "value21");
Assertions.assertEquals(json1.get("b"), "value22");
Assertions.assertEquals(json1.get("c"), "value3");
Assertions.assertEquals(json1.getObj("a"), "value21");
Assertions.assertEquals(json1.getObj("b"), "value22");
Assertions.assertEquals(json1.getObj("c"), "value3");
}
@Test
public void parseStringTest() {
final String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}";
final OldJSONObject jsonObject = JSONUtil.parseObj(jsonStr);
Assertions.assertEquals(jsonObject.get("a"), "value1");
Assertions.assertEquals(jsonObject.get("b"), "value2");
Assertions.assertEquals(jsonObject.get("c"), "value3");
Assertions.assertEquals(jsonObject.get("d"), true);
final JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
Assertions.assertEquals(jsonObject.getObj("a"), "value1");
Assertions.assertEquals(jsonObject.getObj("b"), "value2");
Assertions.assertEquals(jsonObject.getObj("c"), "value3");
Assertions.assertEquals(jsonObject.getObj("d"), true);
Assertions.assertTrue(jsonObject.containsKey("e"));
Assertions.assertNull(jsonObject.get("e"));
@ -124,7 +124,7 @@ public class JSONObjectTest {
public void parseStringTest2() {
final String jsonStr = "{\"file_name\":\"RMM20180127009_731.000\",\"error_data\":\"201121151350701001252500000032 18973908335 18973908335 13601893517 201711211700152017112115135420171121 6594000000010100000000000000000000000043190101701001910072 100001100 \",\"error_code\":\"F140\",\"error_info\":\"最早发送时间格式错误该字段可以为空当不为空时正确填写格式为“YYYYMMDDHHMISS”\",\"app_name\":\"inter-pre-check\"}";
//noinspection MismatchedQueryAndUpdateOfCollection
final OldJSONObject json = new OldJSONObject(jsonStr);
final JSONObject json = JSONUtil.parseObj(jsonStr);
Assertions.assertEquals("F140", json.getStr("error_code"));
Assertions.assertEquals("最早发送时间格式错误该字段可以为空当不为空时正确填写格式为“YYYYMMDDHHMISS”", json.getStr("error_info"));
}
@ -133,7 +133,7 @@ public class JSONObjectTest {
public void parseStringTest3() {
final String jsonStr = "{\"test\":\"体”、“文\"}";
//noinspection MismatchedQueryAndUpdateOfCollection
final OldJSONObject json = new OldJSONObject(jsonStr);
final JSONObject json = JSONUtil.parseObj(jsonStr);
Assertions.assertEquals("体”、“文", json.getStr("test"));
}
@ -141,8 +141,8 @@ public class JSONObjectTest {
public void parseStringTest4() {
final String jsonStr = "{'msg':'这里还没有内容','data':{'cards':[]},'ok':0}";
//noinspection MismatchedQueryAndUpdateOfCollection
final OldJSONObject json = new OldJSONObject(jsonStr);
Assertions.assertEquals(new Integer(0), json.getInt("ok"));
final JSONObject json = JSONUtil.parseObj(jsonStr);
Assertions.assertEquals(Integer.valueOf(0), json.getInt("ok"));
Assertions.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
}
@ -150,8 +150,8 @@ public class JSONObjectTest {
public void parseBytesTest() {
final String jsonStr = "{'msg':'这里还没有内容','data':{'cards':[]},'ok':0}";
//noinspection MismatchedQueryAndUpdateOfCollection
final OldJSONObject json = new OldJSONObject(jsonStr.getBytes(StandardCharsets.UTF_8));
Assertions.assertEquals(new Integer(0), json.getInt("ok"));
final JSONObject json = JSONUtil.parseObj(jsonStr.getBytes(StandardCharsets.UTF_8));
Assertions.assertEquals(Integer.valueOf(0), json.getInt("ok"));
Assertions.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
}
@ -161,8 +161,8 @@ public class JSONObjectTest {
final StringReader stringReader = new StringReader(jsonStr);
//noinspection MismatchedQueryAndUpdateOfCollection
final OldJSONObject json = new OldJSONObject(stringReader);
Assertions.assertEquals(new Integer(0), json.getInt("ok"));
final JSONObject json = JSONUtil.parseObj(stringReader);
Assertions.assertEquals(Integer.valueOf(0), json.getInt("ok"));
Assertions.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
}
@ -172,8 +172,8 @@ public class JSONObjectTest {
final ByteArrayInputStream in = new ByteArrayInputStream(jsonStr.getBytes(StandardCharsets.UTF_8));
//noinspection MismatchedQueryAndUpdateOfCollection
final OldJSONObject json = new OldJSONObject(in);
Assertions.assertEquals(new Integer(0), json.getInt("ok"));
final JSONObject json = JSONUtil.parseObj(in);
Assertions.assertEquals(Integer.valueOf(0), json.getInt("ok"));
Assertions.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
}
@ -182,15 +182,15 @@ public class JSONObjectTest {
//在5.3.2之前</div>中的/会被转义修复此bug的单元测试
final String jsonStr = "{\"a\":\"<div>aaa</div>\"}";
//noinspection MismatchedQueryAndUpdateOfCollection
final OldJSONObject json = new OldJSONObject(jsonStr);
final JSONObject json = JSONUtil.parseObj(jsonStr);
Assertions.assertEquals("<div>aaa</div>", json.getObj("a"));
Assertions.assertEquals(jsonStr, json.toString());
}
@Test
public void toBeanTest() {
final OldJSONObject subJson = JSONUtil.ofObj().set("value1", "strValue1").set("value2", "234");
final OldJSONObject json = JSONUtil.ofObj(JSONConfig.of().setIgnoreError(true)).set("strValue", "strTest").set("intValue", 123)
final JSONObject subJson = JSONUtil.ofObj().set("value1", "strValue1").set("value2", "234");
final JSONObject json = JSONUtil.ofObj(JSONConfig.of().setIgnoreError(true)).set("strValue", "strTest").set("intValue", 123)
// 测试空字符串转对象
.set("doubleValue", "")
.set("beanValue", subJson)
@ -209,7 +209,7 @@ public class JSONObjectTest {
@Test
public void toBeanNullStrTest() {
final OldJSONObject json = JSONUtil.ofObj(JSONConfig.of().setIgnoreError(true))//
final JSONObject json = JSONUtil.ofObj(JSONConfig.of().setIgnoreError(true))//
.set("strValue", "null")//
.set("intValue", 123)//
// 子对象对应"null"字符串如果忽略错误跳过否则抛出转换异常
@ -231,7 +231,7 @@ public class JSONObjectTest {
userA.setDate(new Date());
userA.setSqs(ListUtil.of(new Seq("seq1"), new Seq("seq2")));
final OldJSONObject json = JSONUtil.parseObj(userA);
final JSONObject json = JSONUtil.parseObj(userA);
final UserA userA2 = json.toBean(UserA.class);
// 测试数组
Assertions.assertEquals("seq1", userA2.getSqs().get(0).getSeq());
@ -257,7 +257,7 @@ public class JSONObjectTest {
@Test
public void toBeanTest5() {
final String readUtf8Str = ResourceUtil.readUtf8Str("suiteReport.json");
final OldJSONObject json = JSONUtil.parseObj(readUtf8Str);
final JSONObject json = JSONUtil.parseObj(readUtf8Str);
final SuiteReport bean = json.toBean(SuiteReport.class);
// 第一层
@ -276,7 +276,7 @@ public class JSONObjectTest {
*/
@Test
public void toBeanTest6() {
final OldJSONObject json = JSONUtil.ofObj()
final JSONObject json = JSONUtil.ofObj()
.set("targetUrl", "http://test.com")
.set("success", "true")
.set("result", JSONUtil.ofObj()
@ -313,7 +313,7 @@ public class JSONObjectTest {
userA.setDate(new Date());
userA.setSqs(ListUtil.of(new Seq(null), new Seq("seq2")));
final OldJSONObject json = JSONUtil.parseObj(userA, false);
final JSONObject json = JSONUtil.parseObj(userA, false);
Assertions.assertTrue(json.containsKey("a"));
Assertions.assertTrue(json.getJSONArray("sqs").getJSONObject(0).containsKey("seq"));
@ -328,9 +328,9 @@ public class JSONObjectTest {
bean.setStrValue("strTest");
bean.setTestEnum(TestEnum.TYPE_B);
final OldJSONObject json = JSONUtil.parseObj(bean, false);
final JSONObject json = JSONUtil.parseObj(bean, false);
// 枚举转换检查更新枚举原样保存在writer时调用toString
Assertions.assertEquals(TestEnum.TYPE_B, json.get("testEnum"));
Assertions.assertEquals(TestEnum.TYPE_B, json.getObj("testEnum"));
final TestBean bean2 = json.toBean(TestBean.class);
Assertions.assertEquals(bean.toString(), bean2.toString());
@ -338,7 +338,7 @@ public class JSONObjectTest {
@Test
public void parseBeanTest3() {
final OldJSONObject json = JSONUtil.ofObj()
final JSONObject json = JSONUtil.ofObj()
.set("code", 22)
.set("data", "{\"jobId\": \"abc\", \"videoUrl\": \"http://a.com/a.mp4\"}");
@ -355,7 +355,7 @@ public class JSONObjectTest {
userA.setName("nameTest");
userA.setDate(new Date());
final OldJSONObject userAJson = JSONUtil.parseObj(userA);
final JSONObject userAJson = JSONUtil.parseObj(userA);
final UserB userB = JSONUtil.toBean(userAJson, UserB.class);
Assertions.assertEquals(userA.getName(), userB.getName());
@ -369,9 +369,8 @@ public class JSONObjectTest {
userA.setName("nameTest");
userA.setDate(DateUtil.parse("2018-10-25"));
final OldJSONObject userAJson = JSONUtil.parseObj(userA);
// 自定义日期格式
userAJson.setDateFormat("yyyy-MM-dd");
final JSONObject userAJson = JSONUtil.parseObj(userA, JSONConfig.of().setDateFormat("yyyy-MM-dd"));
final UserA bean = JSONUtil.toBean(userAJson.toString(), UserA.class);
Assertions.assertEquals(DateUtil.parse("2018-10-25"), bean.getDate());
@ -379,7 +378,7 @@ public class JSONObjectTest {
@Test
public void beanTransTest3() {
final OldJSONObject userAJson = JSONUtil.ofObj()
final JSONObject userAJson = JSONUtil.ofObj()
.set("a", "AValue")
.set("name", "nameValue")
.set("date", "08:00:00");
@ -394,10 +393,10 @@ public class JSONObjectTest {
userA.setName("nameTest");
userA.setDate(new Date());
final OldJSONObject userAJson = JSONUtil.parseObj(userA);
final JSONObject userAJson = JSONUtil.parseObj(userA);
Assertions.assertFalse(userAJson.containsKey("a"));
final OldJSONObject userAJsonWithNullValue = JSONUtil.parseObj(userA, false);
final JSONObject userAJsonWithNullValue = JSONUtil.parseObj(userA, false);
Assertions.assertTrue(userAJsonWithNullValue.containsKey("a"));
Assertions.assertTrue(userAJsonWithNullValue.containsKey("sqs"));
}
@ -405,7 +404,7 @@ public class JSONObjectTest {
@Test
public void specialCharTest() {
final String json = "{\"pattern\": \"[abc]\b\u2001\", \"pattern2Json\": {\"patternText\": \"[ab]\\b\"}}";
final OldJSONObject obj = JSONUtil.parseObj(json);
final JSONObject obj = JSONUtil.parseObj(json);
Assertions.assertEquals("[abc]\\b\\u2001", obj.getStrEscaped("pattern"));
Assertions.assertEquals("{\"patternText\":\"[ab]\\b\"}", obj.getStrEscaped("pattern2Json"));
}
@ -413,7 +412,7 @@ public class JSONObjectTest {
@Test
public void getStrTest() {
final String json = "{\"name\": \"yyb\\nbbb\"}";
final OldJSONObject jsonObject = JSONUtil.parseObj(json);
final JSONObject jsonObject = JSONUtil.parseObj(json);
// 没有转义按照默认规则显示
Assertions.assertEquals("yyb\nbbb", jsonObject.getStr("name"));
@ -430,16 +429,16 @@ public class JSONObjectTest {
beanWithAlias.setValue1("张三");
beanWithAlias.setValue2(35);
final OldJSONObject jsonObject = JSONUtil.parseObj(beanWithAlias);
final JSONObject jsonObject = JSONUtil.parseObj(beanWithAlias);
Assertions.assertEquals("张三", jsonObject.getStr("name"));
Assertions.assertEquals(new Integer(35), jsonObject.getInt("age"));
Assertions.assertEquals(Integer.valueOf(35), jsonObject.getInt("age"));
final OldJSONObject json = JSONUtil.ofObj()
final JSONObject json = JSONUtil.ofObj()
.set("name", "张三")
.set("age", 35);
final BeanWithAlias bean = JSONUtil.toBean(Objects.requireNonNull(json).toString(), BeanWithAlias.class);
Assertions.assertEquals("张三", bean.getValue1());
Assertions.assertEquals(new Integer(35), bean.getValue2());
Assertions.assertEquals(Integer.valueOf(35), bean.getValue2());
}
@Test
@ -447,7 +446,7 @@ public class JSONObjectTest {
final JSONConfig jsonConfig = JSONConfig.of();
jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
final OldJSONObject json = new OldJSONObject(jsonConfig);
final JSONObject json = new JSONObject(jsonConfig);
json.append("date", DateUtil.parse("2020-06-05 11:16:11"));
json.append("bbb", "222");
json.append("aaa", "123");
@ -460,7 +459,7 @@ public class JSONObjectTest {
jsonConfig.setDateFormat("yyyy#MM#dd");
final Date date = DateUtil.parse("2020-06-05 11:16:11");
final OldJSONObject json = new OldJSONObject(jsonConfig);
final JSONObject json = new JSONObject(jsonConfig);
json.set("date", date);
json.set("bbb", "222");
json.set("aaa", "123");
@ -470,7 +469,7 @@ public class JSONObjectTest {
Assertions.assertEquals(jsonStr, json.toString());
// 解析测试
final OldJSONObject parse = JSONUtil.parseObj(jsonStr, jsonConfig);
final JSONObject parse = JSONUtil.parseObj(jsonStr, jsonConfig);
Assertions.assertEquals(DateUtil.beginOfDay(date), parse.getDate("date"));
}
@ -480,13 +479,13 @@ public class JSONObjectTest {
final JSONConfig jsonConfig = JSONConfig.of().setDateFormat("#sss");
final Date date = DateUtil.parse("2020-06-05 11:16:11");
final OldJSONObject json = new OldJSONObject(jsonConfig);
final JSONObject json = new JSONObject(jsonConfig);
json.set("date", date);
Assertions.assertEquals("{\"date\":1591326971}", json.toString());
// 解析测试
final OldJSONObject parse = JSONUtil.parseObj(json.toString(), jsonConfig);
final JSONObject parse = JSONUtil.parseObj(json.toString(), jsonConfig);
Assertions.assertEquals(date, DateUtil.date(parse.getDate("date")));
}
@ -496,7 +495,7 @@ public class JSONObjectTest {
jsonConfig.setDateFormat("#sss");
final Date date = DateUtil.parse("2020-06-05 11:16:11");
final OldJSONObject json = new OldJSONObject(jsonConfig);
final JSONObject json = new JSONObject(jsonConfig);
json.set("date", date);
json.set("bbb", "222");
json.set("aaa", "123");
@ -506,14 +505,14 @@ public class JSONObjectTest {
Assertions.assertEquals(jsonStr, json.toString());
// 解析测试
final OldJSONObject parse = JSONUtil.parseObj(jsonStr, jsonConfig);
final JSONObject parse = JSONUtil.parseObj(jsonStr, jsonConfig);
Assertions.assertEquals(date, parse.getDate("date"));
}
@Test
public void getTimestampTest() {
final String timeStr = "1970-01-01 00:00:00";
final OldJSONObject jsonObject = JSONUtil.ofObj().set("time", timeStr);
final JSONObject jsonObject = JSONUtil.ofObj().set("time", timeStr);
final Timestamp time = jsonObject.get("time", Timestamp.class);
Assertions.assertEquals("1970-01-01 00:00:00.0", time.toString());
}
@ -559,7 +558,7 @@ public class JSONObjectTest {
@Test
public void parseBeanSameNameTest() {
final SameNameBean sameNameBean = new SameNameBean();
final OldJSONObject parse = JSONUtil.parseObj(sameNameBean);
final JSONObject parse = JSONUtil.parseObj(sameNameBean);
Assertions.assertEquals("123", parse.getStr("username"));
Assertions.assertEquals("abc", parse.getStr("userName"));
@ -599,7 +598,7 @@ public class JSONObjectTest {
final Set<Map.Entry<String, String>> entries = of.entrySet();
final Map.Entry<String, String> next = entries.iterator().next();
final OldJSONObject jsonObject = JSONUtil.parseObj(next);
final JSONObject jsonObject = JSONUtil.parseObj(next);
Assertions.assertEquals("{\"test\":\"testValue\"}", jsonObject.toString());
}
@ -607,7 +606,7 @@ public class JSONObjectTest {
public void createJSONObjectTest() {
Assertions.assertThrows(JSONException.class, ()->{
// 集合类不支持转为JSONObject
new OldJSONObject(new JSONArray(), JSONConfig.of());
JSONUtil.parseObj(new JSONArray(), JSONConfig.of());
});
}
@ -622,7 +621,7 @@ public class JSONObjectTest {
@Test
public void appendTest() {
final OldJSONObject jsonObject = JSONUtil.ofObj().append("key1", "value1");
final JSONObject jsonObject = JSONUtil.ofObj().append("key1", "value1");
Assertions.assertEquals("{\"key1\":\"value1\"}", jsonObject.toString());
jsonObject.append("key1", "value2");
@ -634,7 +633,7 @@ public class JSONObjectTest {
@Test
public void putByPathTest() {
final OldJSONObject json = new OldJSONObject();
final JSONObject json = new JSONObject();
json.putByPath("aa.bb", "BB");
Assertions.assertEquals("{\"aa\":{\"bb\":\"BB\"}}", json.toString());
}
@ -655,7 +654,7 @@ public class JSONObjectTest {
@Test
public void filterIncludeTest() {
final OldJSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
.set("a", "value1")
.set("b", "value2")
.set("c", "value3")
@ -667,7 +666,7 @@ public class JSONObjectTest {
@Test
public void filterExcludeTest() {
final OldJSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
.set("a", "value1")
.set("b", "value2")
.set("c", "value3")
@ -679,7 +678,7 @@ public class JSONObjectTest {
@Test
public void editTest() {
final OldJSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
.set("a", "value1")
.set("b", "value2")
.set("c", "value3")
@ -699,7 +698,7 @@ public class JSONObjectTest {
@Test
public void toUnderLineCaseTest() {
final OldJSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
.set("aKey", "value1")
.set("bJob", "value2")
.set("cGood", "value3")
@ -714,7 +713,7 @@ public class JSONObjectTest {
@Test
public void nullToEmptyTest() {
final OldJSONObject json1 = JSONUtil.ofObj(JSONConfig.of().setIgnoreNullValue(false))
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of().setIgnoreNullValue(false))
.set("a", null)
.set("b", "value2");
@ -729,22 +728,22 @@ public class JSONObjectTest {
public void parseFilterTest() {
final String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}";
//noinspection MismatchedQueryAndUpdateOfCollection
final OldJSONObject jsonObject = new OldJSONObject(jsonStr, null, (pair)-> "b".equals(pair.getKey()));
final JSONObject jsonObject = JSONUtil.parseObj(jsonStr, null, (pair)-> "b".equals(pair.getKey()));
Assertions.assertEquals(1, jsonObject.size());
Assertions.assertEquals("value2", jsonObject.get("b"));
Assertions.assertEquals("value2", jsonObject.getObj("b"));
}
@Test
public void parseFilterEditTest() {
final String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}";
//noinspection MismatchedQueryAndUpdateOfCollection
final OldJSONObject jsonObject = new OldJSONObject(jsonStr, null, (pair)-> {
final JSONObject jsonObject = JSONUtil.parseObj(jsonStr, null, (pair)-> {
if("b".equals(pair.getKey())){
final JSONPrimitive primitive = (JSONPrimitive) pair.getValue();
pair.setValue(primitive.getValue() + "_edit");
}
return true;
});
Assertions.assertEquals("value2_edit", jsonObject.get("b"));
Assertions.assertEquals("value2_edit", jsonObject.getObj("b"));
}
}

View File

@ -27,7 +27,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
public class JSONTokenerTest {
@Test
void parseTest() {
final OldJSONObject jsonObject = JSONUtil.parseObj(ResourceUtil.getUtf8Reader("issue1200.json"));
final JSONObject jsonObject = JSONUtil.parseObj(ResourceUtil.getUtf8Reader("issue1200.json"));
assertNotNull(jsonObject);
}

View File

@ -124,7 +124,7 @@ public class JSONUtilTest {
@Test
public void parseNumberToJSONObjectTest() {
assertThrows(JSONException.class, () -> {
final OldJSONObject json = JSONUtil.parseObj(123L);
final JSONObject json = JSONUtil.parseObj(123L);
Assertions.assertNotNull(json);
});
}
@ -134,8 +134,8 @@ public class JSONUtilTest {
*/
@Test
public void parseNumberToJSONObjectTest2() {
final OldJSONObject json = JSONUtil.parseObj(123L, JSONConfig.of().setIgnoreError(true));
assertEquals(new OldJSONObject(), json);
final JSONObject json = JSONUtil.parseObj(123L, JSONConfig.of().setIgnoreError(true));
assertEquals(new JSONObject(), json);
}
@Test
@ -169,7 +169,7 @@ public class JSONUtilTest {
data.put("model", model);
data.put("model2", model);
final OldJSONObject jsonObject = JSONUtil.parseObj(data);
final JSONObject jsonObject = JSONUtil.parseObj(data);
Assertions.assertTrue(jsonObject.containsKey("model"));
assertEquals(1, jsonObject.getJSONObject("model").getInt("type").intValue());
@ -180,7 +180,7 @@ public class JSONUtilTest {
@Test
public void toJsonStrTest3() {
// 验证某个字段为JSON字符串时转义是否规范
final OldJSONObject object = new OldJSONObject(JSONConfig.of().setIgnoreError(true));
final JSONObject object = new JSONObject(JSONConfig.of().setIgnoreError(true));
object.set("name", "123123");
object.set("value", "\\");
object.set("value2", "</");
@ -188,12 +188,12 @@ public class JSONUtilTest {
final HashMap<String, String> map = MapUtil.newHashMap();
map.put("user", object.toString());
final OldJSONObject json = JSONUtil.parseObj(map);
assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"</\"}", json.get("user"));
final JSONObject json = JSONUtil.parseObj(map);
assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"</\"}", json.getObj("user"));
assertEquals("{\"user\":\"{\\\"name\\\":\\\"123123\\\",\\\"value\\\":\\\"\\\\\\\\\\\",\\\"value2\\\":\\\"</\\\"}\"}", json.toString());
final OldJSONObject json2 = JSONUtil.parseObj(json.toString());
assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"</\"}", json2.get("user"));
final JSONObject json2 = JSONUtil.parseObj(json.toString());
assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"</\"}", json2.getObj("user"));
}
@Test
@ -230,7 +230,7 @@ public class JSONUtilTest {
final UserC user = JSONUtil.toBean(json, UserC.class);
Assertions.assertNotNull(user.getProp());
final String prop = user.getProp();
final OldJSONObject propJson = JSONUtil.parseObj(prop);
final JSONObject propJson = JSONUtil.parseObj(prop);
assertEquals("", propJson.getStr("gender"));
assertEquals(18, propJson.getInt("age").intValue());
// Assertions.assertEquals("{\"age\":18,\"gender\":\"\"}", user.getProp());
@ -239,31 +239,31 @@ public class JSONUtilTest {
@Test
public void getStrTest() {
final String html = "{\"name\":\"Something must have been changed since you leave\"}";
final OldJSONObject jsonObject = JSONUtil.parseObj(html);
final JSONObject jsonObject = JSONUtil.parseObj(html);
assertEquals("Something must have been changed since you leave", jsonObject.getStr("name"));
}
@Test
public void getStrTest2() {
final String html = "{\"name\":\"Something\\u00a0must have been changed since you leave\"}";
final OldJSONObject jsonObject = JSONUtil.parseObj(html);
final JSONObject jsonObject = JSONUtil.parseObj(html);
assertEquals("Something\\u00a0must\\u00a0have\\u00a0been\\u00a0changed\\u00a0since\\u00a0you\\u00a0leave", jsonObject.getStrEscaped("name"));
}
@Test
public void parseFromXmlTest() {
final String s = "<sfzh>640102197312070614</sfzh><sfz>640102197312070614X</sfz><name>aa</name><gender>1</gender>";
final OldJSONObject json = JSONUtil.parseFromXml(s);
assertEquals(640102197312070614L, json.get("sfzh"));
assertEquals("640102197312070614X", json.get("sfz"));
assertEquals("aa", json.get("name"));
assertEquals(1, json.get("gender"));
final JSONObject json = JSONUtil.parseFromXml(s);
assertEquals(640102197312070614L, json.getObj("sfzh"));
assertEquals("640102197312070614X", json.getObj("sfz"));
assertEquals("aa", json.getObj("name"));
assertEquals(1, json.getObj("gender"));
}
@Test
public void doubleTest() {
final String json = "{\"test\": 12.00}";
final OldJSONObject jsonObject = JSONUtil.parseObj(json);
final JSONObject jsonObject = JSONUtil.parseObj(json);
//noinspection BigDecimalMethodWithoutRoundingCalled
assertEquals("12.00", jsonObject.getBigDecimal("test").setScale(2).toString());
}
@ -271,12 +271,12 @@ public class JSONUtilTest {
@Test
public void setStripTrailingZerosTest() {
// 默认去除多余的0
final OldJSONObject jsonObjectDefault = JSONUtil.ofObj()
final JSONObject jsonObjectDefault = JSONUtil.ofObj()
.set("test2", 12.00D);
assertEquals("{\"test2\":12}", jsonObjectDefault.toString());
// 不去除多余的0
final OldJSONObject jsonObject = JSONUtil.ofObj(JSONConfig.of().setStripTrailingZeros(false))
final JSONObject jsonObject = JSONUtil.ofObj(JSONConfig.of().setStripTrailingZeros(false))
.set("test2", 12.00D);
assertEquals("{\"test2\":12.0}", jsonObject.toString());
@ -288,7 +288,7 @@ public class JSONUtilTest {
@Test
public void parseObjTest() {
// 测试转义
final OldJSONObject jsonObject = JSONUtil.parseObj("{\n" +
final JSONObject jsonObject = JSONUtil.parseObj("{\n" +
" \"test\": \"\\\\地库地库\",\n" +
"}");
@ -299,7 +299,7 @@ public class JSONUtilTest {
public void sqlExceptionTest() {
//https://github.com/dromara/hutool/issues/1399
// SQLException实现了Iterable接口默认是遍历之会栈溢出修正后只返回string
final OldJSONObject set = JSONUtil.ofObj().set("test", new SQLException("test"));
final JSONObject set = JSONUtil.ofObj().set("test", new SQLException("test"));
assertEquals("{\"test\":\"java.sql.SQLException: test\"}", set.toString());
}
@ -312,7 +312,7 @@ public class JSONUtilTest {
@Test
public void toXmlTest() {
final OldJSONObject obj = JSONUtil.ofObj();
final JSONObject obj = JSONUtil.ofObj();
obj.set("key1", "v1")
.set("key2", ListUtil.view("a", "b", "c"));
final String xmlStr = JSONUtil.toXmlStr(obj);

View File

@ -26,7 +26,7 @@ public class JSONWriterTest {
@Test
public void writeDateTest() {
final OldJSONObject 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"));
// 日期原样写入
@ -37,7 +37,7 @@ public class JSONWriterTest {
Assertions.assertEquals("{\"date\":\"2022-09-30\"}", jsonObject.toString());
// 自定义日期格式解析生效
final OldJSONObject parse = JSONUtil.parseObj(jsonObject.toString(), JSONConfig.of().setDateFormat("yyyy-MM-dd"));
Assertions.assertEquals(String.class, parse.get("date").getClass());
final JSONObject parse = JSONUtil.parseObj(jsonObject.toString(), JSONConfig.of().setDateFormat("yyyy-MM-dd"));
Assertions.assertEquals(String.class, parse.getObj("date").getClass());
}
}

View File

@ -47,7 +47,7 @@ public class ParseBeanTest {
final A a = new A();
a.setBs(ListUtil.of(b1, b2));
final OldJSONObject json = JSONUtil.parseObj(a);
final JSONObject json = JSONUtil.parseObj(a);
final A a1 = JSONUtil.toBean(json, A.class);
Assertions.assertEquals(json.toString(), JSONUtil.toJsonStr(a1));
}

View File

@ -28,7 +28,7 @@ public class Pr3067Test {
@Test
public void getListByPathTest1() {
final OldJSONObject json = JSONUtil.parseObj(ResourceUtil.readUtf8Str("test_json_path_001.json"));
final JSONObject json = JSONUtil.parseObj(ResourceUtil.readUtf8Str("test_json_path_001.json"));
final List<TestUser> resultList = json.getByPath("testUserList[1].testArray",
new TypeReference<List<TestUser>>() {});

View File

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

View File

@ -35,7 +35,7 @@ public class TransientTest {
detailBill.setBizNo("bizNo");
//noinspection MismatchedQueryAndUpdateOfCollection
final OldJSONObject jsonObject = new OldJSONObject(detailBill,
final JSONObject jsonObject = JSONUtil.parseObj(detailBill,
JSONConfig.of().setTransientSupport(false));
Assertions.assertEquals("{\"id\":\"3243\",\"bizNo\":\"bizNo\"}", jsonObject.toString());
}
@ -47,7 +47,7 @@ public class TransientTest {
detailBill.setBizNo("bizNo");
//noinspection MismatchedQueryAndUpdateOfCollection
final OldJSONObject jsonObject = new OldJSONObject(detailBill,
final JSONObject jsonObject = JSONUtil.parseObj(detailBill,
JSONConfig.of().setTransientSupport(true));
Assertions.assertEquals("{\"bizNo\":\"bizNo\"}", jsonObject.toString());
}
@ -58,7 +58,7 @@ public class TransientTest {
detailBill.setId("3243");
detailBill.setBizNo("bizNo");
final OldJSONObject jsonObject = new OldJSONObject(detailBill,
final JSONObject jsonObject = JSONUtil.parseObj(detailBill,
JSONConfig.of().setTransientSupport(false));
final Bill bill = jsonObject.toBean(Bill.class);
@ -72,7 +72,7 @@ public class TransientTest {
detailBill.setId("3243");
detailBill.setBizNo("bizNo");
final OldJSONObject jsonObject = new OldJSONObject(detailBill,
final JSONObject jsonObject = JSONUtil.parseObj(detailBill,
JSONConfig.of().setTransientSupport(true));
final Bill bill = jsonObject.toBean(Bill.class);

View File

@ -16,11 +16,11 @@
package org.dromara.hutool.json.jwt;
import lombok.Data;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.date.TimeUtil;
import org.dromara.hutool.json.OldJSONObject;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import lombok.Data;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -40,7 +40,7 @@ public class IssueI6IS5BTest {
jwtToken.setIat(iat);
final String token = JWTUtil.createToken(JSONUtil.parseObj(jwtToken), "123".getBytes(StandardCharsets.UTF_8));
Assertions.assertEquals("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2Nzc3NzI4MDB9.SXU_mm1wT5lNoK-Dq5Y8f3BItv_44zuAlyeWLqajpXg", token);
final OldJSONObject payloads = JWTUtil.parseToken(token).getPayloads();
final JSONObject payloads = JWTUtil.parseToken(token).getPayloads();
Assertions.assertEquals("{\"iat\":1677772800}", payloads.toString());
final JwtToken o = payloads.toBean(JwtToken.class);
Assertions.assertEquals(iat, o.getIat());
@ -58,7 +58,7 @@ public class IssueI6IS5BTest {
jwtToken.setIat(iat);
final String token = JWTUtil.createToken(JSONUtil.parseObj(jwtToken), "123".getBytes(StandardCharsets.UTF_8));
Assertions.assertEquals("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2Nzc3NzI4MDB9.SXU_mm1wT5lNoK-Dq5Y8f3BItv_44zuAlyeWLqajpXg", token);
final OldJSONObject payloads = JWTUtil.parseToken(token).getPayloads();
final JSONObject payloads = JWTUtil.parseToken(token).getPayloads();
Assertions.assertEquals("{\"iat\":1677772800}", payloads.toString());
final JwtToken2 o = payloads.toBean(JwtToken2.class);
Assertions.assertEquals(iat, o.getIat());

View File

@ -16,7 +16,7 @@
package org.dromara.hutool.json.jwt;
import org.dromara.hutool.json.OldJSONObject;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -28,7 +28,7 @@ public class IssueI76TRQTest {
@Test
void createTokenTest() {
final String str = "{\"editorConfig\":{\"mode\":\"edit\",\"callbackUrl\":\"http://172.16.30.53:8080/OnlineEditorsExampleJava/IndexServlet?type\\u003dtrack\\u0026fileName\\u003dnew.docx\\u0026userAddress\\u003d172.16.30.53\",\"lang\":\"zh\",\"createUrl\":\"http://172.16.30.53:8080/OnlineEditorsExampleJava/EditorServlet?fileExt\\u003ddocx\",\"templates\":[{\"image\":\"\",\"title\":\"Blank\",\"url\":\"http://172.16.30.53:8080/OnlineEditorsExampleJava/EditorServlet?fileExt\\u003ddocx\"},{\"image\":\"http://172.16.30.53:8080/OnlineEditorsExampleJava/css/img/file_docx.svg\",\"title\":\"With sample content\",\"url\":\"http://172.16.30.53:8080/OnlineEditorsExampleJava/EditorServlet?fileExt\\u003ddocx\\u0026sample\\u003dtrue\"}],\"user\":{\"id\":\"uid-1\",\"name\":\"John Smith\",\"group\":\"\"},\"customization\":{\"goback\":{\"url\":\"http://172.16.30.53:8080/OnlineEditorsExampleJava/IndexServlet\"},\"forcesave\":false,\"submitForm\":false,\"about\":true,\"comments\":true,\"feedback\":true}},\"documentType\":\"word\",\"document\":{\"title\":\"new.docx\",\"url\":\"http://172.16.30.53:8080/OnlineEditorsExampleJava/IndexServlet?type\\u003ddownload\\u0026fileName\\u003dnew.docx\\u0026userAddress\\u003d172.16.30.53\",\"directUrl\":\"\",\"fileType\":\"docx\",\"key\":\"1956415572\",\"info\":{\"owner\":\"Me\",\"uploaded\":\"Fri May 19 2023\"},\"permissions\":{\"comment\":true,\"copy\":true,\"download\":true,\"edit\":true,\"print\":true,\"fillForms\":true,\"modifyFilter\":true,\"modifyContentControl\":true,\"review\":true,\"chat\":true,\"commentGroups\":{}}},\"type\":\"desktop\"}";
final OldJSONObject payload = JSONUtil.parseObj(str);
final JSONObject payload = JSONUtil.parseObj(str);
final String token = JWTUtil.createToken(payload, "123456".getBytes());
Assertions.assertNotNull(token);

View File

@ -18,7 +18,7 @@ package org.dromara.hutool.json.reader;
import org.dromara.hutool.json.JSON;
import org.dromara.hutool.json.JSONConfig;
import org.dromara.hutool.json.OldJSONObject;
import org.dromara.hutool.json.JSONObject;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -34,6 +34,6 @@ public class JSONParserTest {
@Test
void nextToTest() {
final String jsonStr = "{\"a\": 1}";
JSONParser.of(new JSONTokener(jsonStr), JSONConfig.of()).parseTo(new OldJSONObject());
JSONParser.of(new JSONTokener(jsonStr), JSONConfig.of()).parseTo(new JSONObject());
}
}

View File

@ -16,11 +16,11 @@
package org.dromara.hutool.json.test.bean;
import org.dromara.hutool.json.OldJSONObject;
import lombok.Data;
import org.dromara.hutool.json.JSONObject;
@Data
public class JSONBean {
private int code;
private OldJSONObject data;
private JSONObject data;
}

View File

@ -16,7 +16,7 @@
package org.dromara.hutool.json.xml;
import org.dromara.hutool.json.OldJSONObject;
import org.dromara.hutool.json.JSONObject;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -24,7 +24,7 @@ public class Issue3560Test {
@Test
public void toJSONObjectTest() {
final String inPara= "<ROOT><ID>002317479934367853</ID><CONTENT><![CDATA[asdfadf&amp;21sdgzxv&amp;aasfasf]]></CONTENT></ROOT>";
final OldJSONObject json = JSONXMLUtil.toJSONObject(inPara, ParseConfig.of().setKeepStrings(true));
final JSONObject json = JSONXMLUtil.toJSONObject(inPara, ParseConfig.of().setKeepStrings(true));
Assertions.assertEquals("{\"ROOT\":{\"ID\":\"002317479934367853\",\"CONTENT\":\"asdfadf&amp;21sdgzxv&amp;aasfasf\"}}", json.toString());
}
}

View File

@ -16,7 +16,7 @@
package org.dromara.hutool.json.xml;
import org.dromara.hutool.json.OldJSONObject;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -25,7 +25,7 @@ public class XMLTest {
@Test
public void toXmlTest(){
final OldJSONObject put = JSONUtil.ofObj()
final JSONObject put = JSONUtil.ofObj()
.set("aaa", "你好")
.set("键2", "test");
final String s = JSONUtil.toXmlStr(put);
@ -35,7 +35,7 @@ public class XMLTest {
@Test
public void escapeTest(){
final String xml = "<a>•</a>";
final OldJSONObject jsonObject = JSONXMLUtil.toJSONObject(xml);
final JSONObject jsonObject = JSONXMLUtil.toJSONObject(xml);
Assertions.assertEquals("{\"a\":\"\"}", jsonObject.toString());
@ -45,7 +45,7 @@ public class XMLTest {
@Test
public void xmlContentTest(){
final OldJSONObject jsonObject = JSONUtil.ofObj().set("content","123456");
final JSONObject jsonObject = JSONUtil.ofObj().set("content","123456");
String xml = JSONXMLUtil.toXml(jsonObject);
Assertions.assertEquals("123456", xml);