mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
remove JSONStringer
This commit is contained in:
parent
ee13716d42
commit
70b4f773e4
@ -56,9 +56,9 @@ public class CompositeConverter implements Converter, Serializable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获得单例的 ConverterRegistry
|
* 获得单例的 CompositeConverter
|
||||||
*
|
*
|
||||||
* @return ConverterRegistry
|
* @return CompositeConverter
|
||||||
*/
|
*/
|
||||||
public static CompositeConverter getInstance() {
|
public static CompositeConverter getInstance() {
|
||||||
return SingletonHolder.INSTANCE;
|
return SingletonHolder.INSTANCE;
|
||||||
|
@ -19,7 +19,7 @@ package org.dromara.hutool.http;
|
|||||||
import org.dromara.hutool.core.collection.ListUtil;
|
import org.dromara.hutool.core.collection.ListUtil;
|
||||||
import org.dromara.hutool.core.net.url.UrlQuery;
|
import org.dromara.hutool.core.net.url.UrlQuery;
|
||||||
import org.dromara.hutool.core.util.CharsetUtil;
|
import org.dromara.hutool.core.util.CharsetUtil;
|
||||||
import org.dromara.hutool.json.JSONObject;
|
import org.dromara.hutool.json.OldJSONObject;
|
||||||
import org.junit.jupiter.api.Assertions;
|
import org.junit.jupiter.api.Assertions;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
@ -30,7 +30,7 @@ public class IssueIAFKWPTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void urlWithFormTest() {
|
void urlWithFormTest() {
|
||||||
final JSONObject obj = new JSONObject();
|
final OldJSONObject obj = new OldJSONObject();
|
||||||
obj.put("fields", ListUtil.of("1", "2", "good"));
|
obj.put("fields", ListUtil.of("1", "2", "good"));
|
||||||
|
|
||||||
final Map<String, Object> params = new HashMap<>();
|
final Map<String, Object> params = new HashMap<>();
|
||||||
|
@ -28,8 +28,8 @@ import org.dromara.hutool.core.math.NumberUtil;
|
|||||||
import org.dromara.hutool.core.text.CharUtil;
|
import org.dromara.hutool.core.text.CharUtil;
|
||||||
import org.dromara.hutool.core.text.StrUtil;
|
import org.dromara.hutool.core.text.StrUtil;
|
||||||
import org.dromara.hutool.core.text.split.SplitUtil;
|
import org.dromara.hutool.core.text.split.SplitUtil;
|
||||||
|
import org.dromara.hutool.core.util.ObjUtil;
|
||||||
import org.dromara.hutool.json.reader.JSONTokener;
|
import org.dromara.hutool.json.reader.JSONTokener;
|
||||||
import org.dromara.hutool.json.serializer.JSONStringer;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.StringWriter;
|
import java.io.StringWriter;
|
||||||
@ -94,10 +94,8 @@ public final class InternalJSONUtil {
|
|||||||
/**
|
/**
|
||||||
* 值转为String,用于JSON中。规则为:
|
* 值转为String,用于JSON中。规则为:
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>对象如果实现了{@link JSONStringer}接口,调用{@link JSONStringer#toJSONString()}方法</li>
|
|
||||||
* <li>对象如果实现了{@link JSONStringer}接口,调用{@link JSONStringer#toJSONString()}方法</li>
|
|
||||||
* <li>对象如果是数组或Collection,包装为{@link JSONArray}</li>
|
* <li>对象如果是数组或Collection,包装为{@link JSONArray}</li>
|
||||||
* <li>对象如果是Map,包装为{@link JSONObject}</li>
|
* <li>对象如果是Map,包装为{@link OldJSONObject}</li>
|
||||||
* <li>对象如果是数字,使用{@link NumberUtil#toStr(Number)}转换为字符串</li>
|
* <li>对象如果是数字,使用{@link NumberUtil#toStr(Number)}转换为字符串</li>
|
||||||
* <li>其他情况调用toString并使用双引号包装</li>
|
* <li>其他情况调用toString并使用双引号包装</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
@ -110,19 +108,13 @@ public final class InternalJSONUtil {
|
|||||||
if (value == null) {
|
if (value == null) {
|
||||||
return StrUtil.NULL;
|
return StrUtil.NULL;
|
||||||
}
|
}
|
||||||
if (value instanceof JSONStringer) {
|
if (value instanceof Number) {
|
||||||
try {
|
|
||||||
return ((JSONStringer) value).toJSONString();
|
|
||||||
} catch (final Exception e) {
|
|
||||||
throw new JSONException(e);
|
|
||||||
}
|
|
||||||
} else if (value instanceof Number) {
|
|
||||||
return NumberUtil.toStr((Number) value);
|
return NumberUtil.toStr((Number) value);
|
||||||
} else if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) {
|
} else if (value instanceof Boolean || value instanceof OldJSONObject || value instanceof JSONArray) {
|
||||||
return value.toString();
|
return value.toString();
|
||||||
} else if (value instanceof Map) {
|
} else if (value instanceof Map) {
|
||||||
final Map<?, ?> map = (Map<?, ?>) value;
|
final Map<?, ?> map = (Map<?, ?>) value;
|
||||||
return new JSONObject(map).toString();
|
return new OldJSONObject(map).toString();
|
||||||
} else if (value instanceof Collection) {
|
} else if (value instanceof Collection) {
|
||||||
final Collection<?> coll = (Collection<?>) value;
|
final Collection<?> coll = (Collection<?>) value;
|
||||||
return new JSONArray(coll).toString();
|
return new JSONArray(coll).toString();
|
||||||
@ -143,15 +135,15 @@ public final class InternalJSONUtil {
|
|||||||
* @param value 值
|
* @param value 值
|
||||||
* @param predicate 属性过滤器,{@link Predicate#test(Object)}为{@code true}保留
|
* @param predicate 属性过滤器,{@link Predicate#test(Object)}为{@code true}保留
|
||||||
*/
|
*/
|
||||||
public static void propertyPut(final JSONObject jsonObject, final Object key, final Object value, final Predicate<MutableEntry<Object, Object>> predicate) {
|
public static void propertyPut(final OldJSONObject jsonObject, final Object key, final Object value, final Predicate<MutableEntry<Object, Object>> predicate) {
|
||||||
final String[] path = SplitUtil.splitToArray(ConvertUtil.toStr(key), StrUtil.DOT);
|
final String[] path = SplitUtil.splitToArray(ConvertUtil.toStr(key), StrUtil.DOT);
|
||||||
final int last = path.length - 1;
|
final int last = path.length - 1;
|
||||||
JSONObject target = jsonObject;
|
OldJSONObject target = jsonObject;
|
||||||
for (int i = 0; i < last; i += 1) {
|
for (int i = 0; i < last; i += 1) {
|
||||||
final String segment = path[i];
|
final String segment = path[i];
|
||||||
JSONObject nextTarget = target.getJSONObject(segment);
|
OldJSONObject nextTarget = target.getJSONObject(segment);
|
||||||
if (nextTarget == null) {
|
if (nextTarget == null) {
|
||||||
nextTarget = new JSONObject(target.config());
|
nextTarget = new OldJSONObject(target.config());
|
||||||
target.set(segment, nextTarget, predicate);
|
target.set(segment, nextTarget, predicate);
|
||||||
}
|
}
|
||||||
target = nextTarget;
|
target = nextTarget;
|
||||||
@ -282,7 +274,8 @@ public final class InternalJSONUtil {
|
|||||||
* @param config JSON配置项,{@code null}则使用默认配置
|
* @param config JSON配置项,{@code null}则使用默认配置
|
||||||
* @return Map
|
* @return Map
|
||||||
*/
|
*/
|
||||||
static Map<String, Object> createRawMap(final int capacity, JSONConfig config) {
|
@Deprecated
|
||||||
|
static Map<String, Object> createRawMapOld(final int capacity, JSONConfig config) {
|
||||||
final Map<String, Object> rawHashMap;
|
final Map<String, Object> rawHashMap;
|
||||||
if (null == config) {
|
if (null == config) {
|
||||||
config = JSONConfig.of();
|
config = JSONConfig.of();
|
||||||
@ -304,6 +297,32 @@ public final class InternalJSONUtil {
|
|||||||
return rawHashMap;
|
return rawHashMap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据配置创建对应的原始Map
|
||||||
|
*
|
||||||
|
* @param capacity 初始大小
|
||||||
|
* @param config JSON配置项,{@code null}则使用默认配置
|
||||||
|
* @return Map
|
||||||
|
*/
|
||||||
|
static Map<String, JSON> createRawMap(final int capacity, final JSONConfig config) {
|
||||||
|
final Map<String, JSON> rawHashMap;
|
||||||
|
final Comparator<String> keyComparator = ObjUtil.apply(config, JSONConfig::getKeyComparator);
|
||||||
|
if (null != config && 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;
|
||||||
|
}
|
||||||
|
|
||||||
// --------------------------------------------------------------------------------------------- Private method start
|
// --------------------------------------------------------------------------------------------- Private method start
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -31,7 +31,7 @@ import java.util.function.Predicate;
|
|||||||
/**
|
/**
|
||||||
* JSON树模型接口,表示树中的一个节点。实现包括:
|
* JSON树模型接口,表示树中的一个节点。实现包括:
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>{@link JSONObject}表示键值对形式的节点</li>
|
* <li>{@link OldJSONObject}表示键值对形式的节点</li>
|
||||||
* <li>{@link JSONArray}表示列表形式的节点</li>
|
* <li>{@link JSONArray}表示列表形式的节点</li>
|
||||||
* <li>{@link JSONPrimitive}表示数字、Boolean、字符串形式的节点</li>
|
* <li>{@link JSONPrimitive}表示数字、Boolean、字符串形式的节点</li>
|
||||||
* <li>{@code null}表示空节点</li>
|
* <li>{@code null}表示空节点</li>
|
||||||
|
@ -259,11 +259,11 @@ public class JSONArray implements JSON, JSONGetter<Integer>, List<Object>, Rando
|
|||||||
* @return A JSONObject,无名或值返回null
|
* @return A JSONObject,无名或值返回null
|
||||||
* @throws JSONException 如果任何一个名为null
|
* @throws JSONException 如果任何一个名为null
|
||||||
*/
|
*/
|
||||||
public JSONObject toJSONObject(final JSONArray names) throws JSONException {
|
public OldJSONObject toJSONObject(final JSONArray names) throws JSONException {
|
||||||
if (names == null || names.size() == 0 || this.size() == 0) {
|
if (names == null || names.size() == 0 || this.size() == 0) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
final JSONObject jo = new JSONObject(this.config);
|
final OldJSONObject jo = new OldJSONObject(this.config);
|
||||||
for (int i = 0; i < names.size(); i += 1) {
|
for (int i = 0; i < names.size(); i += 1) {
|
||||||
jo.set(names.getStr(i), this.getObj(i));
|
jo.set(names.getStr(i), this.getObj(i));
|
||||||
}
|
}
|
||||||
|
@ -92,21 +92,21 @@ public interface JSONGetter<K> extends TypeGetter<K> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 获得JSONObject对象<br>
|
* 获得JSONObject对象<br>
|
||||||
* 如果值为其它类型对象,尝试转换为{@link JSONObject}返回,否则抛出异常
|
* 如果值为其它类型对象,尝试转换为{@link OldJSONObject}返回,否则抛出异常
|
||||||
*
|
*
|
||||||
* @param key KEY
|
* @param key KEY
|
||||||
* @return JSONObject对象,如果值为{@code null},返回{@code null},非JSONObject类型,尝试转换,转换失败抛出异常
|
* @return JSONObject对象,如果值为{@code null},返回{@code null},非JSONObject类型,尝试转换,转换失败抛出异常
|
||||||
*/
|
*/
|
||||||
default JSONObject getJSONObject(final K key) {
|
default OldJSONObject getJSONObject(final K key) {
|
||||||
final Object object = this.getObj(key);
|
final Object object = this.getObj(key);
|
||||||
if (ObjUtil.isNull(object)) {
|
if (ObjUtil.isNull(object)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (object instanceof JSON) {
|
if (object instanceof JSON) {
|
||||||
return (JSONObject) object;
|
return (OldJSONObject) object;
|
||||||
}
|
}
|
||||||
return new JSONObject(object, config());
|
return new OldJSONObject(object, config());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -120,7 +120,7 @@ public interface JSONGetter<K> extends TypeGetter<K> {
|
|||||||
* @since 3.1.1
|
* @since 3.1.1
|
||||||
*/
|
*/
|
||||||
default <T> T getBean(final K key, final Class<T> beanType) {
|
default <T> T getBean(final K key, final Class<T> beanType) {
|
||||||
final JSONObject obj = getJSONObject(key);
|
final OldJSONObject obj = getJSONObject(key);
|
||||||
return (null == obj) ? null : obj.toBean(beanType);
|
return (null == obj) ? null : obj.toBean(beanType);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013-2024 Hutool Team and hutool.cn
|
* Copyright (c) 2024 Hutool Team and hutool.cn
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -16,40 +16,16 @@
|
|||||||
|
|
||||||
package org.dromara.hutool.json;
|
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.lang.mutable.MutableEntry;
|
||||||
import org.dromara.hutool.core.map.MapUtil;
|
import org.dromara.hutool.core.map.MapUtil;
|
||||||
import org.dromara.hutool.core.map.MapWrapper;
|
import org.dromara.hutool.core.map.MapWrapper;
|
||||||
import org.dromara.hutool.core.util.ObjUtil;
|
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 org.dromara.hutool.json.writer.JSONWriter;
|
||||||
|
|
||||||
import java.io.StringWriter;
|
|
||||||
import java.io.Writer;
|
import java.io.Writer;
|
||||||
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;
|
import java.util.function.Predicate;
|
||||||
|
|
||||||
/**
|
public class JSONObject extends MapWrapper<String, JSON> implements JSON{
|
||||||
* JSON对象<br>
|
|
||||||
* 例:<br>
|
|
||||||
*
|
|
||||||
* <pre>
|
|
||||||
* json = new JSONObject().put("JSON", "Hello, World!").toString();
|
|
||||||
* </pre>
|
|
||||||
*
|
|
||||||
* @author looly
|
|
||||||
*/
|
|
||||||
public class JSONObject extends MapWrapper<String, Object> implements JSON, JSONGetter<String> {
|
|
||||||
private static final long serialVersionUID = -330220388580734346L;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 默认初始大小
|
* 默认初始大小
|
||||||
@ -60,12 +36,6 @@ public class JSONObject extends MapWrapper<String, Object> implements JSON, JSON
|
|||||||
* 配置项
|
* 配置项
|
||||||
*/
|
*/
|
||||||
private JSONConfig config;
|
private JSONConfig config;
|
||||||
/**
|
|
||||||
* 对象转换和包装,用于将Java对象和值转换为JSON值
|
|
||||||
*/
|
|
||||||
private JSONValueMapper valueMapper;
|
|
||||||
|
|
||||||
// -------------------------------------------------------------------------------------------------------------------- Constructor start
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构造,初始容量为 {@link #DEFAULT_CAPACITY},KEY有序
|
* 构造,初始容量为 {@link #DEFAULT_CAPACITY},KEY有序
|
||||||
@ -89,371 +59,17 @@ public class JSONObject extends MapWrapper<String, Object> implements JSON, JSON
|
|||||||
*
|
*
|
||||||
* @param capacity 初始大小
|
* @param capacity 初始大小
|
||||||
* @param config JSON配置项,{@code null}则使用默认配置
|
* @param config JSON配置项,{@code null}则使用默认配置
|
||||||
* @since 4.1.19
|
|
||||||
*/
|
*/
|
||||||
public JSONObject(final int capacity, final JSONConfig config) {
|
public JSONObject(final int capacity, final JSONConfig config) {
|
||||||
super(InternalJSONUtil.createRawMap(capacity, ObjUtil.defaultIfNull(config, JSONConfig.of())));
|
super(InternalJSONUtil.createRawMap(capacity, config));
|
||||||
this.config = ObjUtil.defaultIfNull(config, JSONConfig.of());
|
this.config = ObjUtil.defaultIfNull(config, JSONConfig::of);
|
||||||
this.valueMapper = JSONValueMapper.of(this.config);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 构建JSONObject,JavaBean默认忽略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 JSONObject(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 JSONObject(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 JSONObject(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
|
@Override
|
||||||
public JSONConfig config() {
|
public JSONConfig config() {
|
||||||
return this.config;
|
return this.config;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 设置转为字符串时的日期格式,默认为时间戳(null值)<br>
|
|
||||||
* 此方法设置的日期格式仅对转换为JSON字符串有效,对解析JSON为bean无效。
|
|
||||||
*
|
|
||||||
* @param format 格式,null表示使用时间戳
|
|
||||||
* @return this
|
|
||||||
* @since 4.1.19
|
|
||||||
*/
|
|
||||||
public JSONObject 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 JSONObject 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 JSONObject 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 JSONObject 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 JSONObject 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 JSONObject 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 JSONObject 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 JSONObject 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 JSONObject 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 StringWriter sw = new StringWriter();
|
|
||||||
synchronized (sw.getBuffer()) {
|
|
||||||
return this.write(sw, indentFactor, 0, predicate).toString();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 将JSON内容写入Writer<br>
|
|
||||||
* 支持过滤器,即选择哪些字段或值不写出
|
|
||||||
*
|
|
||||||
* @param writer writer
|
|
||||||
* @param indentFactor 缩进因子,定义每一级别增加的缩进量
|
|
||||||
* @param indent 本级别缩进量
|
|
||||||
* @param predicate 过滤器,同时可以修改编辑键和值
|
|
||||||
* @return Writer
|
|
||||||
* @throws JSONException JSON相关异常
|
|
||||||
* @since 5.7.15
|
|
||||||
*/
|
|
||||||
@Override
|
@Override
|
||||||
public Writer write(final Writer writer, final int indentFactor, final int indent, final Predicate<MutableEntry<Object, Object>> predicate) throws JSONException {
|
public Writer write(final Writer writer, final int indentFactor, final int indent, final Predicate<MutableEntry<Object, Object>> predicate) throws JSONException {
|
||||||
final JSONWriter jsonWriter = JSONWriter.of(writer, indentFactor, indent, config)
|
final JSONWriter jsonWriter = JSONWriter.of(writer, indentFactor, indent, config)
|
||||||
@ -463,51 +79,4 @@ public class JSONObject extends MapWrapper<String, Object> implements JSON, JSON
|
|||||||
// 此处不关闭Writer,考虑writer后续还需要填内容
|
// 此处不关闭Writer,考虑writer后续还需要填内容
|
||||||
return writer;
|
return writer;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public JSONObject clone() throws CloneNotSupportedException {
|
|
||||||
final JSONObject clone = (JSONObject) 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));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -18,9 +18,9 @@ package org.dromara.hutool.json;
|
|||||||
|
|
||||||
import org.dromara.hutool.core.lang.Assert;
|
import org.dromara.hutool.core.lang.Assert;
|
||||||
import org.dromara.hutool.core.lang.mutable.MutableEntry;
|
import org.dromara.hutool.core.lang.mutable.MutableEntry;
|
||||||
import org.dromara.hutool.json.writer.GlobalValueWriters;
|
|
||||||
import org.dromara.hutool.json.writer.JSONValueWriter;
|
|
||||||
import org.dromara.hutool.json.writer.JSONWriter;
|
import org.dromara.hutool.json.writer.JSONWriter;
|
||||||
|
import org.dromara.hutool.json.writer.ValueWriter;
|
||||||
|
import org.dromara.hutool.json.writer.ValueWriterManager;
|
||||||
|
|
||||||
import java.io.StringWriter;
|
import java.io.StringWriter;
|
||||||
import java.io.Writer;
|
import java.io.Writer;
|
||||||
@ -119,7 +119,7 @@ public class JSONPrimitive implements JSON {
|
|||||||
final JSONWriter jsonWriter = JSONWriter.of(writer, indentFactor, indent, config);
|
final JSONWriter jsonWriter = JSONWriter.of(writer, indentFactor, indent, config);
|
||||||
|
|
||||||
// 自定义规则
|
// 自定义规则
|
||||||
final JSONValueWriter valueWriter = GlobalValueWriters.get(value);
|
final ValueWriter valueWriter = ValueWriterManager.getInstance().get(value);
|
||||||
if (null != valueWriter) {
|
if (null != valueWriter) {
|
||||||
valueWriter.write(jsonWriter, value);
|
valueWriter.write(jsonWriter, value);
|
||||||
return writer;
|
return writer;
|
||||||
|
@ -23,9 +23,9 @@ import org.dromara.hutool.core.reflect.TypeReference;
|
|||||||
import org.dromara.hutool.core.text.StrUtil;
|
import org.dromara.hutool.core.text.StrUtil;
|
||||||
import org.dromara.hutool.core.util.ObjUtil;
|
import org.dromara.hutool.core.util.ObjUtil;
|
||||||
import org.dromara.hutool.json.convert.JSONConverter;
|
import org.dromara.hutool.json.convert.JSONConverter;
|
||||||
import org.dromara.hutool.json.writer.GlobalValueWriters;
|
|
||||||
import org.dromara.hutool.json.writer.JSONValueWriter;
|
|
||||||
import org.dromara.hutool.json.writer.JSONWriter;
|
import org.dromara.hutool.json.writer.JSONWriter;
|
||||||
|
import org.dromara.hutool.json.writer.ValueWriter;
|
||||||
|
import org.dromara.hutool.json.writer.ValueWriterManager;
|
||||||
import org.dromara.hutool.json.xml.JSONXMLUtil;
|
import org.dromara.hutool.json.xml.JSONXMLUtil;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
@ -49,8 +49,8 @@ public class JSONUtil {
|
|||||||
*
|
*
|
||||||
* @return JSONObject
|
* @return JSONObject
|
||||||
*/
|
*/
|
||||||
public static JSONObject ofObj() {
|
public static OldJSONObject ofObj() {
|
||||||
return new JSONObject();
|
return new OldJSONObject();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -60,8 +60,8 @@ public class JSONUtil {
|
|||||||
* @return JSONObject
|
* @return JSONObject
|
||||||
* @since 5.2.5
|
* @since 5.2.5
|
||||||
*/
|
*/
|
||||||
public static JSONObject ofObj(final JSONConfig config) {
|
public static OldJSONObject ofObj(final JSONConfig config) {
|
||||||
return new JSONObject(config);
|
return new OldJSONObject(config);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -91,8 +91,8 @@ public class JSONUtil {
|
|||||||
* @param obj Bean对象或者Map
|
* @param obj Bean对象或者Map
|
||||||
* @return JSONObject
|
* @return JSONObject
|
||||||
*/
|
*/
|
||||||
public static JSONObject parseObj(final Object obj) {
|
public static OldJSONObject parseObj(final Object obj) {
|
||||||
return new JSONObject(obj);
|
return new OldJSONObject(obj);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -104,8 +104,8 @@ public class JSONUtil {
|
|||||||
* @return JSONObject
|
* @return JSONObject
|
||||||
* @since 5.3.1
|
* @since 5.3.1
|
||||||
*/
|
*/
|
||||||
public static JSONObject parseObj(final Object obj, final JSONConfig config) {
|
public static OldJSONObject parseObj(final Object obj, final JSONConfig config) {
|
||||||
return new JSONObject(obj, config);
|
return new OldJSONObject(obj, config);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -116,8 +116,8 @@ public class JSONUtil {
|
|||||||
* @return JSONObject
|
* @return JSONObject
|
||||||
* @since 3.0.9
|
* @since 3.0.9
|
||||||
*/
|
*/
|
||||||
public static JSONObject parseObj(final Object obj, final boolean ignoreNullValue) {
|
public static OldJSONObject parseObj(final Object obj, final boolean ignoreNullValue) {
|
||||||
return new JSONObject(obj, JSONConfig.of().setIgnoreNullValue(ignoreNullValue));
|
return new OldJSONObject(obj, JSONConfig.of().setIgnoreNullValue(ignoreNullValue));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -185,7 +185,7 @@ public class JSONUtil {
|
|||||||
* @param xmlStr XML字符串
|
* @param xmlStr XML字符串
|
||||||
* @return JSONObject
|
* @return JSONObject
|
||||||
*/
|
*/
|
||||||
public static JSONObject parseFromXml(final String xmlStr) {
|
public static OldJSONObject parseFromXml(final String xmlStr) {
|
||||||
return JSONXMLUtil.toJSONObject(xmlStr);
|
return JSONXMLUtil.toJSONObject(xmlStr);
|
||||||
}
|
}
|
||||||
// -------------------------------------------------------------------- Parse end
|
// -------------------------------------------------------------------- Parse end
|
||||||
@ -212,7 +212,7 @@ public class JSONUtil {
|
|||||||
* @return JSONObject
|
* @return JSONObject
|
||||||
* @throws IORuntimeException IO异常
|
* @throws IORuntimeException IO异常
|
||||||
*/
|
*/
|
||||||
public static JSONObject readJSONObject(final File file, final Charset charset) throws IORuntimeException {
|
public static OldJSONObject readJSONObject(final File file, final Charset charset) throws IORuntimeException {
|
||||||
return FileUtil.read(file, charset, JSONUtil::parseObj);
|
return FileUtil.read(file, charset, JSONUtil::parseObj);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -261,7 +261,7 @@ public class JSONUtil {
|
|||||||
*/
|
*/
|
||||||
public static String toJsonStr(final Object obj, final JSONConfig jsonConfig) {
|
public static String toJsonStr(final Object obj, final JSONConfig jsonConfig) {
|
||||||
// 自定义规则,优先级高于全局规则
|
// 自定义规则,优先级高于全局规则
|
||||||
final JSONValueWriter valueWriter = GlobalValueWriters.get(obj);
|
final ValueWriter valueWriter = ValueWriterManager.getInstance().get(obj);
|
||||||
if (null != valueWriter) {
|
if (null != valueWriter) {
|
||||||
final StringWriter stringWriter = new StringWriter();
|
final StringWriter stringWriter = new StringWriter();
|
||||||
final JSONWriter jsonWriter = JSONWriter.of(stringWriter, 0, 0, null);
|
final JSONWriter jsonWriter = JSONWriter.of(stringWriter, 0, 0, null);
|
||||||
@ -307,7 +307,7 @@ public class JSONUtil {
|
|||||||
* @return JSONObject
|
* @return JSONObject
|
||||||
* @since 4.0.8
|
* @since 4.0.8
|
||||||
*/
|
*/
|
||||||
public static JSONObject xmlToJson(final String xml) {
|
public static OldJSONObject xmlToJson(final String xml) {
|
||||||
return JSONXMLUtil.toJSONObject(xml);
|
return JSONXMLUtil.toJSONObject(xml);
|
||||||
}
|
}
|
||||||
// -------------------------------------------------------------------- toString end
|
// -------------------------------------------------------------------- toString end
|
||||||
@ -480,7 +480,7 @@ public class JSONUtil {
|
|||||||
* <ul>
|
* <ul>
|
||||||
* <li>null</li>
|
* <li>null</li>
|
||||||
* <li>{@link JSONArray#isEmpty()}</li>
|
* <li>{@link JSONArray#isEmpty()}</li>
|
||||||
* <li>{@link JSONObject#isEmpty()}</li>
|
* <li>{@link OldJSONObject#isEmpty()}</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
*
|
*
|
||||||
* @param json JSONObject或JSONArray
|
* @param json JSONObject或JSONArray
|
||||||
@ -490,8 +490,8 @@ public class JSONUtil {
|
|||||||
if (null == json) {
|
if (null == json) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (json instanceof JSONObject) {
|
if (json instanceof OldJSONObject) {
|
||||||
return ((JSONObject) json).isEmpty();
|
return ((OldJSONObject) json).isEmpty();
|
||||||
} else if (json instanceof JSONArray) {
|
} else if (json instanceof JSONArray) {
|
||||||
return ((JSONArray) json).isEmpty();
|
return ((JSONArray) json).isEmpty();
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,513 @@
|
|||||||
|
/*
|
||||||
|
* 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.io.StringWriter;
|
||||||
|
import java.io.Writer;
|
||||||
|
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("JSON", "Hello, World!").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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建JSONObject,JavaBean默认忽略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 StringWriter sw = new StringWriter();
|
||||||
|
synchronized (sw.getBuffer()) {
|
||||||
|
return this.write(sw, indentFactor, 0, predicate).toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将JSON内容写入Writer<br>
|
||||||
|
* 支持过滤器,即选择哪些字段或值不写出
|
||||||
|
*
|
||||||
|
* @param writer writer
|
||||||
|
* @param indentFactor 缩进因子,定义每一级别增加的缩进量
|
||||||
|
* @param indent 本级别缩进量
|
||||||
|
* @param predicate 过滤器,同时可以修改编辑键和值
|
||||||
|
* @return Writer
|
||||||
|
* @throws JSONException JSON相关异常
|
||||||
|
* @since 5.7.15
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public Writer write(final Writer writer, final int indentFactor, final int indent, final Predicate<MutableEntry<Object, Object>> predicate) throws JSONException {
|
||||||
|
final JSONWriter jsonWriter = JSONWriter.of(writer, indentFactor, indent, config)
|
||||||
|
.beginObj();
|
||||||
|
this.forEach((key, value) -> jsonWriter.writeField(new MutableEntry<>(key, value), predicate));
|
||||||
|
jsonWriter.end();
|
||||||
|
// 此处不关闭Writer,考虑writer后续还需要填内容
|
||||||
|
return writer;
|
||||||
|
}
|
||||||
|
|
||||||
|
@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));
|
||||||
|
}
|
||||||
|
}
|
@ -69,7 +69,7 @@ public class JSONConverter implements Converter, Serializable {
|
|||||||
public static JSONConverter of(final JSONConfig config) {
|
public static JSONConverter of(final JSONConfig config) {
|
||||||
final JSONConverter jsonConverter = new JSONConverter(config);
|
final JSONConverter jsonConverter = new JSONConverter(config);
|
||||||
jsonConverter.registerConverter = new RegisterConverter(jsonConverter)
|
jsonConverter.registerConverter = new RegisterConverter(jsonConverter)
|
||||||
.register(JSONObject.class, INSTANCE)
|
.register(OldJSONObject.class, INSTANCE)
|
||||||
.register(JSONArray.class, INSTANCE)
|
.register(JSONArray.class, INSTANCE)
|
||||||
.register(JSONPrimitive.class, INSTANCE);
|
.register(JSONPrimitive.class, INSTANCE);
|
||||||
jsonConverter.specialConverter = new SpecialConverter(jsonConverter);
|
jsonConverter.specialConverter = new SpecialConverter(jsonConverter);
|
||||||
@ -94,10 +94,6 @@ public class JSONConverter implements Converter, Serializable {
|
|||||||
if (null == value) {
|
if (null == value) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
if (value instanceof JSONStringer) {
|
|
||||||
// 被JSONString包装的对象,获取其原始类型
|
|
||||||
value = ((JSONStringer) value).getRaw();
|
|
||||||
}
|
|
||||||
|
|
||||||
// JSON转对象
|
// JSON转对象
|
||||||
if (value instanceof JSON) {
|
if (value instanceof JSON) {
|
||||||
@ -173,11 +169,11 @@ public class JSONConverter implements Converter, Serializable {
|
|||||||
return toJSON((CharSequence) obj);
|
return toJSON((CharSequence) obj);
|
||||||
} else if (obj instanceof MapWrapper) {
|
} else if (obj instanceof MapWrapper) {
|
||||||
// MapWrapper实现了Iterable会被当作JSONArray,此处做修正
|
// MapWrapper实现了Iterable会被当作JSONArray,此处做修正
|
||||||
json = new JSONObject(obj, config);
|
json = new OldJSONObject(obj, config);
|
||||||
} else if (obj instanceof Iterable || obj instanceof Iterator || ArrayUtil.isArray(obj)) {// 列表
|
} else if (obj instanceof Iterable || obj instanceof Iterator || ArrayUtil.isArray(obj)) {// 列表
|
||||||
json = new JSONArray(obj, config);
|
json = new JSONArray(obj, config);
|
||||||
} else {// 对象
|
} else {// 对象
|
||||||
json = new JSONObject(obj, config);
|
json = new OldJSONObject(obj, config);
|
||||||
}
|
}
|
||||||
|
|
||||||
return json;
|
return json;
|
||||||
|
@ -21,7 +21,7 @@ import org.dromara.hutool.core.date.format.GlobalCustomFormat;
|
|||||||
import org.dromara.hutool.core.lang.Assert;
|
import org.dromara.hutool.core.lang.Assert;
|
||||||
import org.dromara.hutool.core.map.MapUtil;
|
import org.dromara.hutool.core.map.MapUtil;
|
||||||
import org.dromara.hutool.json.JSONConfig;
|
import org.dromara.hutool.json.JSONConfig;
|
||||||
import org.dromara.hutool.json.JSONObject;
|
import org.dromara.hutool.json.OldJSONObject;
|
||||||
import org.dromara.hutool.json.JSONUtil;
|
import org.dromara.hutool.json.JSONUtil;
|
||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
@ -40,7 +40,7 @@ public class Claims implements Serializable {
|
|||||||
// 时间使用秒级时间戳表示
|
// 时间使用秒级时间戳表示
|
||||||
private final JSONConfig CONFIG = JSONConfig.of().setDateFormat(GlobalCustomFormat.FORMAT_SECONDS);
|
private final JSONConfig CONFIG = JSONConfig.of().setDateFormat(GlobalCustomFormat.FORMAT_SECONDS);
|
||||||
|
|
||||||
private JSONObject claimJSON;
|
private OldJSONObject claimJSON;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 增加Claims属性,如果属性值为{@code null},则移除这个属性
|
* 增加Claims属性,如果属性值为{@code null},则移除这个属性
|
||||||
@ -86,7 +86,7 @@ public class Claims implements Serializable {
|
|||||||
*
|
*
|
||||||
* @return JSON字符串
|
* @return JSON字符串
|
||||||
*/
|
*/
|
||||||
public JSONObject getClaimsJson() {
|
public OldJSONObject getClaimsJson() {
|
||||||
init();
|
init();
|
||||||
return this.claimJSON;
|
return this.claimJSON;
|
||||||
}
|
}
|
||||||
@ -109,7 +109,7 @@ public class Claims implements Serializable {
|
|||||||
|
|
||||||
private void init(){
|
private void init(){
|
||||||
if(null == this.claimJSON){
|
if(null == this.claimJSON){
|
||||||
this.claimJSON = new JSONObject(CONFIG);
|
this.claimJSON = new OldJSONObject(CONFIG);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -24,7 +24,7 @@ import org.dromara.hutool.core.lang.Assert;
|
|||||||
import org.dromara.hutool.core.text.StrUtil;
|
import org.dromara.hutool.core.text.StrUtil;
|
||||||
import org.dromara.hutool.core.text.split.SplitUtil;
|
import org.dromara.hutool.core.text.split.SplitUtil;
|
||||||
import org.dromara.hutool.core.util.CharsetUtil;
|
import org.dromara.hutool.core.util.CharsetUtil;
|
||||||
import org.dromara.hutool.json.JSONObject;
|
import org.dromara.hutool.json.OldJSONObject;
|
||||||
import org.dromara.hutool.json.jwt.signers.AlgorithmUtil;
|
import org.dromara.hutool.json.jwt.signers.AlgorithmUtil;
|
||||||
import org.dromara.hutool.json.jwt.signers.JWTSigner;
|
import org.dromara.hutool.json.jwt.signers.JWTSigner;
|
||||||
import org.dromara.hutool.json.jwt.signers.JWTSignerUtil;
|
import org.dromara.hutool.json.jwt.signers.JWTSignerUtil;
|
||||||
@ -203,7 +203,7 @@ public class JWT implements RegisteredPayload<JWT> {
|
|||||||
*
|
*
|
||||||
* @return 头信息
|
* @return 头信息
|
||||||
*/
|
*/
|
||||||
public JSONObject getHeaders() {
|
public OldJSONObject getHeaders() {
|
||||||
return this.header.getClaimsJson();
|
return this.header.getClaimsJson();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -265,7 +265,7 @@ public class JWT implements RegisteredPayload<JWT> {
|
|||||||
*
|
*
|
||||||
* @return 载荷信息
|
* @return 载荷信息
|
||||||
*/
|
*/
|
||||||
public JSONObject getPayloads() {
|
public OldJSONObject getPayloads() {
|
||||||
return this.payload.getClaimsJson();
|
return this.payload.getClaimsJson();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -85,12 +85,12 @@ public class JSONObjectMapper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将给定对象转换为{@link JSONObject}
|
* 将给定对象转换为{@link OldJSONObject}
|
||||||
*
|
*
|
||||||
* @param jsonObject 目标{@link JSONObject}
|
* @param jsonObject 目标{@link OldJSONObject}
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
public void mapTo(final JSONObject jsonObject) {
|
public void mapTo(final OldJSONObject jsonObject) {
|
||||||
final Object source = this.source;
|
final Object source = this.source;
|
||||||
if (null == source) {
|
if (null == source) {
|
||||||
return;
|
return;
|
||||||
@ -153,10 +153,10 @@ public class JSONObjectMapper {
|
|||||||
* 从{@link ResourceBundle}转换
|
* 从{@link ResourceBundle}转换
|
||||||
*
|
*
|
||||||
* @param bundle ResourceBundle
|
* @param bundle ResourceBundle
|
||||||
* @param jsonObject {@link JSONObject}
|
* @param jsonObject {@link OldJSONObject}
|
||||||
* @since 5.3.1
|
* @since 5.3.1
|
||||||
*/
|
*/
|
||||||
private void mapFromResourceBundle(final ResourceBundle bundle, final JSONObject jsonObject) {
|
private void mapFromResourceBundle(final ResourceBundle bundle, final OldJSONObject jsonObject) {
|
||||||
final Enumeration<String> keys = bundle.getKeys();
|
final Enumeration<String> keys = bundle.getKeys();
|
||||||
while (keys.hasMoreElements()) {
|
while (keys.hasMoreElements()) {
|
||||||
final String key = keys.nextElement();
|
final String key = keys.nextElement();
|
||||||
@ -170,9 +170,9 @@ public class JSONObjectMapper {
|
|||||||
* 从字符串转换
|
* 从字符串转换
|
||||||
*
|
*
|
||||||
* @param source JSON字符串
|
* @param source JSON字符串
|
||||||
* @param jsonObject {@link JSONObject}
|
* @param jsonObject {@link OldJSONObject}
|
||||||
*/
|
*/
|
||||||
private void mapFromStr(final CharSequence source, final JSONObject jsonObject) {
|
private void mapFromStr(final CharSequence source, final OldJSONObject jsonObject) {
|
||||||
final String jsonStr = StrUtil.trim(source);
|
final String jsonStr = StrUtil.trim(source);
|
||||||
if (StrUtil.startWith(jsonStr, '<')) {
|
if (StrUtil.startWith(jsonStr, '<')) {
|
||||||
// 可能为XML
|
// 可能为XML
|
||||||
@ -188,9 +188,9 @@ public class JSONObjectMapper {
|
|||||||
*
|
*
|
||||||
* @param x JSONTokener
|
* @param x JSONTokener
|
||||||
* @param config JSON配置
|
* @param config JSON配置
|
||||||
* @param jsonObject {@link JSONObject}
|
* @param jsonObject {@link OldJSONObject}
|
||||||
*/
|
*/
|
||||||
private void mapFromTokener(final JSONTokener x, final JSONConfig config, final JSONObject jsonObject) {
|
private void mapFromTokener(final JSONTokener x, final JSONConfig config, final OldJSONObject jsonObject) {
|
||||||
JSONParser.of(x, config).setPredicate(this.predicate).parseTo(jsonObject);
|
JSONParser.of(x, config).setPredicate(this.predicate).parseTo(jsonObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -198,9 +198,9 @@ public class JSONObjectMapper {
|
|||||||
* 从Record转换
|
* 从Record转换
|
||||||
*
|
*
|
||||||
* @param record Record对象
|
* @param record Record对象
|
||||||
* @param jsonObject {@link JSONObject}
|
* @param jsonObject {@link OldJSONObject}
|
||||||
*/
|
*/
|
||||||
private void mapFromRecord(final Object record, final JSONObject jsonObject) {
|
private void mapFromRecord(final Object record, final OldJSONObject jsonObject) {
|
||||||
final Map.Entry<String, Type>[] components = RecordUtil.getRecordComponents(record.getClass());
|
final Map.Entry<String, Type>[] components = RecordUtil.getRecordComponents(record.getClass());
|
||||||
|
|
||||||
String key;
|
String key;
|
||||||
@ -214,9 +214,9 @@ public class JSONObjectMapper {
|
|||||||
* 从Bean转换
|
* 从Bean转换
|
||||||
*
|
*
|
||||||
* @param bean Bean对象
|
* @param bean Bean对象
|
||||||
* @param jsonObject {@link JSONObject}
|
* @param jsonObject {@link OldJSONObject}
|
||||||
*/
|
*/
|
||||||
private void mapFromBean(final Object bean, final JSONObject jsonObject) {
|
private void mapFromBean(final Object bean, final OldJSONObject jsonObject) {
|
||||||
final CopyOptions copyOptions = InternalJSONUtil.toCopyOptions(jsonObject.config());
|
final CopyOptions copyOptions = InternalJSONUtil.toCopyOptions(jsonObject.config());
|
||||||
if (null != this.predicate) {
|
if (null != this.predicate) {
|
||||||
copyOptions.setFieldEditor((entry -> this.predicate.test(
|
copyOptions.setFieldEditor((entry -> this.predicate.test(
|
||||||
|
@ -19,8 +19,7 @@ package org.dromara.hutool.json.mapper;
|
|||||||
import org.dromara.hutool.core.array.ArrayUtil;
|
import org.dromara.hutool.core.array.ArrayUtil;
|
||||||
import org.dromara.hutool.core.util.ObjUtil;
|
import org.dromara.hutool.core.util.ObjUtil;
|
||||||
import org.dromara.hutool.json.*;
|
import org.dromara.hutool.json.*;
|
||||||
import org.dromara.hutool.json.serializer.JSONStringer;
|
import org.dromara.hutool.json.writer.ValueWriterManager;
|
||||||
import org.dromara.hutool.json.writer.GlobalValueWriters;
|
|
||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
@ -82,9 +81,8 @@ public class JSONValueMapper implements Serializable {
|
|||||||
// null、JSON、字符串和自定义对象原样存储
|
// null、JSON、字符串和自定义对象原样存储
|
||||||
if (null == object
|
if (null == object
|
||||||
// 当用户自定义了对象的字符串表示形式,则保留这个对象
|
// 当用户自定义了对象的字符串表示形式,则保留这个对象
|
||||||
|| null != GlobalValueWriters.get(object)
|
|| null != ValueWriterManager.getInstance().get(object)
|
||||||
|| object instanceof JSON //
|
|| object instanceof JSON //
|
||||||
|| object instanceof JSONStringer //
|
|
||||||
|| object instanceof CharSequence //
|
|| object instanceof CharSequence //
|
||||||
|| ObjUtil.isBasicType(object) //
|
|| ObjUtil.isBasicType(object) //
|
||||||
) {
|
) {
|
||||||
@ -103,7 +101,7 @@ public class JSONValueMapper implements Serializable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 默认按照JSONObject对待
|
// 默认按照JSONObject对待
|
||||||
return new JSONObject(object, jsonConfig);
|
return new OldJSONObject(object, jsonConfig);
|
||||||
} catch (final Exception exception) {
|
} catch (final Exception exception) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
@ -121,7 +121,7 @@ public class JSONParser {
|
|||||||
}
|
}
|
||||||
switch (tokener.nextClean()) {
|
switch (tokener.nextClean()) {
|
||||||
case CharUtil.DELIM_START:
|
case CharUtil.DELIM_START:
|
||||||
nextTo((JSONObject) json);
|
nextTo((OldJSONObject) json);
|
||||||
break;
|
break;
|
||||||
case CharUtil.BRACKET_START:
|
case CharUtil.BRACKET_START:
|
||||||
nextTo((JSONArray) json);
|
nextTo((JSONArray) json);
|
||||||
@ -146,7 +146,7 @@ public class JSONParser {
|
|||||||
final JSON result;
|
final JSON result;
|
||||||
switch (firstChar) {
|
switch (firstChar) {
|
||||||
case CharUtil.DELIM_START:
|
case CharUtil.DELIM_START:
|
||||||
final JSONObject jsonObject = new JSONObject(config);
|
final OldJSONObject jsonObject = new OldJSONObject(config);
|
||||||
nextTo(jsonObject);
|
nextTo(jsonObject);
|
||||||
result = jsonObject;
|
result = jsonObject;
|
||||||
break;
|
break;
|
||||||
@ -167,7 +167,7 @@ public class JSONParser {
|
|||||||
*
|
*
|
||||||
* @param jsonObject JSON对象
|
* @param jsonObject JSON对象
|
||||||
*/
|
*/
|
||||||
private void nextTo(final JSONObject jsonObject) {
|
private void nextTo(final OldJSONObject jsonObject) {
|
||||||
final JSONTokener tokener = this.tokener;
|
final JSONTokener tokener = this.tokener;
|
||||||
|
|
||||||
char c;
|
char c;
|
||||||
|
@ -17,6 +17,7 @@
|
|||||||
package org.dromara.hutool.json.serializer;
|
package org.dromara.hutool.json.serializer;
|
||||||
|
|
||||||
import org.dromara.hutool.json.JSON;
|
import org.dromara.hutool.json.JSON;
|
||||||
|
import org.dromara.hutool.json.OldJSONObject;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 序列化接口,通过实现此接口,实现自定义的对象转换为JSON的操作
|
* 序列化接口,通过实现此接口,实现自定义的对象转换为JSON的操作
|
||||||
@ -32,7 +33,7 @@ public interface JSONSerializer<V> {
|
|||||||
* <ul>
|
* <ul>
|
||||||
* <li>如果为原始类型,可以转为{@link org.dromara.hutool.json.JSONPrimitive}</li>
|
* <li>如果为原始类型,可以转为{@link org.dromara.hutool.json.JSONPrimitive}</li>
|
||||||
* <li>如果是集合或数组类,可以转为{@link org.dromara.hutool.json.JSONArray}</li>
|
* <li>如果是集合或数组类,可以转为{@link org.dromara.hutool.json.JSONArray}</li>
|
||||||
* <li>如果是Bean或键值对类型,可以转为{@link org.dromara.hutool.json.JSONObject}</li>
|
* <li>如果是Bean或键值对类型,可以转为{@link OldJSONObject}</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
*
|
*
|
||||||
* @param bean 指定类型对象
|
* @param bean 指定类型对象
|
||||||
|
@ -1,47 +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.serializer;
|
|
||||||
|
|
||||||
import org.dromara.hutool.core.lang.wrapper.Wrapper;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* {@code JSONString}接口定义了一个{@code toJSONString()}<br>
|
|
||||||
* 实现此接口的类可以通过实现{@code toJSONString()}方法来改变转JSON字符串的方式。
|
|
||||||
*
|
|
||||||
* @author Looly
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
@FunctionalInterface
|
|
||||||
public interface JSONStringer extends Wrapper<Object> {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 自定义转JSON字符串的方法
|
|
||||||
*
|
|
||||||
* @return JSON字符串
|
|
||||||
*/
|
|
||||||
String toJSONString();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取原始的对象,默认为this
|
|
||||||
*
|
|
||||||
* @return 原始对象
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
default Object getRaw() {
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
}
|
|
@ -161,7 +161,7 @@ public class SerializerManager {
|
|||||||
* @param bean 对象
|
* @param bean 对象
|
||||||
* @return JSONSerializer
|
* @return JSONSerializer
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
@SuppressWarnings({"rawtypes"})
|
||||||
public JSONSerializer<?> getSerializer(final Object bean) {
|
public JSONSerializer<?> getSerializer(final Object bean) {
|
||||||
for (final MatcherJSONSerializer serializer : this.serializerSet) {
|
for (final MatcherJSONSerializer serializer : this.serializerSet) {
|
||||||
if (serializer.match(bean, null)) {
|
if (serializer.match(bean, null)) {
|
||||||
@ -254,17 +254,18 @@ public class SerializerManager {
|
|||||||
* 注册默认的序列化器和反序列化器
|
* 注册默认的序列化器和反序列化器
|
||||||
*/
|
*/
|
||||||
private static void registerDefault() {
|
private static void registerDefault() {
|
||||||
SingletonHolder.INSTANCE.register(LocalDate.class, (JSONSerializer<?>) new TemporalAccessorSerializer(LocalDate.class));
|
final SerializerManager manager = SingletonHolder.INSTANCE;
|
||||||
SingletonHolder.INSTANCE.register(LocalDate.class, (JSONDeserializer<?>) new TemporalAccessorSerializer(LocalDate.class));
|
manager.register(LocalDate.class, (JSONSerializer<?>) new TemporalAccessorSerializer(LocalDate.class));
|
||||||
|
manager.register(LocalDate.class, (JSONDeserializer<?>) new TemporalAccessorSerializer(LocalDate.class));
|
||||||
|
|
||||||
SingletonHolder.INSTANCE.register(LocalTime.class, (JSONSerializer<?>) new TemporalAccessorSerializer(LocalTime.class));
|
manager.register(LocalTime.class, (JSONSerializer<?>) new TemporalAccessorSerializer(LocalTime.class));
|
||||||
SingletonHolder.INSTANCE.register(LocalTime.class, (JSONDeserializer<?>) new TemporalAccessorSerializer(LocalTime.class));
|
manager.register(LocalTime.class, (JSONDeserializer<?>) new TemporalAccessorSerializer(LocalTime.class));
|
||||||
|
|
||||||
SingletonHolder.INSTANCE.register(LocalDateTime.class, (JSONSerializer<?>) new TemporalAccessorSerializer(LocalDateTime.class));
|
manager.register(LocalDateTime.class, (JSONSerializer<?>) new TemporalAccessorSerializer(LocalDateTime.class));
|
||||||
SingletonHolder.INSTANCE.register(LocalDateTime.class, (JSONDeserializer<?>) new TemporalAccessorSerializer(LocalDateTime.class));
|
manager.register(LocalDateTime.class, (JSONDeserializer<?>) new TemporalAccessorSerializer(LocalDateTime.class));
|
||||||
|
|
||||||
SingletonHolder.INSTANCE.register((MatcherJSONSerializer<TimeZone>) TimeZoneSerializer.INSTANCE);
|
manager.register((MatcherJSONSerializer<TimeZone>) TimeZoneSerializer.INSTANCE);
|
||||||
SingletonHolder.INSTANCE.register((MatcherJSONDeserializer<TimeZone>) TimeZoneSerializer.INSTANCE);
|
manager.register((MatcherJSONDeserializer<TimeZone>) TimeZoneSerializer.INSTANCE);
|
||||||
}
|
}
|
||||||
// endregion
|
// endregion
|
||||||
}
|
}
|
||||||
|
@ -66,12 +66,12 @@ public class TemporalAccessorSerializer implements JSONSerializer<TemporalAccess
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public JSON serialize(final TemporalAccessor bean, final JSONContext context) {
|
public JSON serialize(final TemporalAccessor bean, final JSONContext context) {
|
||||||
final JSONObject json;
|
final OldJSONObject json;
|
||||||
final JSON contextJson = context.getContextJson();
|
final JSON contextJson = context.getContextJson();
|
||||||
if(contextJson instanceof JSONObject){
|
if(contextJson instanceof OldJSONObject){
|
||||||
json = (JSONObject) contextJson;
|
json = (OldJSONObject) contextJson;
|
||||||
}else {
|
}else {
|
||||||
json = new JSONObject(7F / 0.75F + 1F, context.config());
|
json = new OldJSONObject(7F / 0.75F + 1F, context.config());
|
||||||
}
|
}
|
||||||
if (bean instanceof LocalDate) {
|
if (bean instanceof LocalDate) {
|
||||||
final LocalDate localDate = (LocalDate) bean;
|
final LocalDate localDate = (LocalDate) bean;
|
||||||
@ -112,7 +112,7 @@ public class TemporalAccessorSerializer implements JSONSerializer<TemporalAccess
|
|||||||
// TODO JSONArray
|
// TODO JSONArray
|
||||||
|
|
||||||
// JSONObject
|
// JSONObject
|
||||||
final JSONObject jsonObject = (JSONObject) json;
|
final OldJSONObject jsonObject = (OldJSONObject) json;
|
||||||
if (LocalDate.class.equals(this.temporalAccessorClass) || LocalDateTime.class.equals(this.temporalAccessorClass)) {
|
if (LocalDate.class.equals(this.temporalAccessorClass) || LocalDateTime.class.equals(this.temporalAccessorClass)) {
|
||||||
// 年
|
// 年
|
||||||
final Integer year = jsonObject.getInt(YEAR_KEY);
|
final Integer year = jsonObject.getInt(YEAR_KEY);
|
||||||
|
@ -1,67 +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.writer;
|
|
||||||
|
|
||||||
import org.dromara.hutool.core.lang.Assert;
|
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 全局自定义对象写出<br>
|
|
||||||
* 用户通过此全局定义,可针对某些特殊对象的写出<br>
|
|
||||||
* 对象定义JSONValueWriter后,JSON中将存储原始对象
|
|
||||||
*
|
|
||||||
* @author looly
|
|
||||||
* @since 6.0.0
|
|
||||||
*/
|
|
||||||
public class GlobalValueWriters {
|
|
||||||
|
|
||||||
private static final List<JSONValueWriter> valueWriterList;
|
|
||||||
|
|
||||||
static {
|
|
||||||
valueWriterList = Collections.synchronizedList(new LinkedList<>());
|
|
||||||
valueWriterList.add(NumberValueWriter.INSTANCE);
|
|
||||||
valueWriterList.add(DateValueWriter.INSTANCE);
|
|
||||||
valueWriterList.add(BooleanValueWriter.INSTANCE);
|
|
||||||
valueWriterList.add(JSONStringValueWriter.INSTANCE);
|
|
||||||
valueWriterList.add(ClassValueWriter.INSTANCE);
|
|
||||||
valueWriterList.add(JdkValueWriter.INSTANCE);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 加入自定义的对象值写出规则,自定义规则总是优先
|
|
||||||
*
|
|
||||||
* @param valueWriter 自定义对象写出实现
|
|
||||||
*/
|
|
||||||
public static void add(final JSONValueWriter valueWriter) {
|
|
||||||
valueWriterList.add(0, Assert.notNull(valueWriter));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取自定义对象值写出规则
|
|
||||||
*
|
|
||||||
* @param value 值,{@code null}表示需要自定义null的输出
|
|
||||||
* @return 自定义的 {@link JSONValueWriter}
|
|
||||||
*/
|
|
||||||
public static JSONValueWriter get(final Object value) {
|
|
||||||
if (value instanceof JSONValueWriter) {
|
|
||||||
return (JSONValueWriter) value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return valueWriterList.stream().filter(writer -> writer.test(value)).findFirst().orElse(null);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,61 +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.writer;
|
|
||||||
|
|
||||||
import org.dromara.hutool.json.JSONException;
|
|
||||||
import org.dromara.hutool.json.serializer.JSONStringer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* {@link JSONStringer}的值写出器
|
|
||||||
*
|
|
||||||
* @author looly
|
|
||||||
* @since 6.0.0
|
|
||||||
*/
|
|
||||||
public class JSONStringValueWriter implements JSONValueWriter {
|
|
||||||
/**
|
|
||||||
* 单例对象
|
|
||||||
*/
|
|
||||||
public static final JSONStringValueWriter INSTANCE = new JSONStringValueWriter();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean test(final Object value) {
|
|
||||||
return value instanceof JSONStringer;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 输出实现了{@link JSONStringer}接口的对象,通过调用{@link JSONStringer#toJSONString()}获取JSON字符串<br>
|
|
||||||
* {@link JSONStringer}按照JSON对象对待,此方法输出的JSON字符串不包装引号。<br>
|
|
||||||
* 如果toJSONString()返回null,调用toString()方法并使用双引号包装。
|
|
||||||
*
|
|
||||||
* @param writer {@link JSONWriter}
|
|
||||||
* @param jsonStringer {@link JSONStringer}
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void write(final JSONWriter writer, final Object jsonStringer) {
|
|
||||||
final String valueStr;
|
|
||||||
try {
|
|
||||||
valueStr = ((JSONStringer)jsonStringer).toJSONString();
|
|
||||||
} catch (final Exception e) {
|
|
||||||
throw new JSONException(e);
|
|
||||||
}
|
|
||||||
if (null != valueStr) {
|
|
||||||
writer.writeRaw(valueStr);
|
|
||||||
} else {
|
|
||||||
writer.writeQuoteStrValue(jsonStringer.toString());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -316,7 +316,7 @@ public class JSONWriter extends Writer {
|
|||||||
final int indent = indentFactor + this.indent;
|
final int indent = indentFactor + this.indent;
|
||||||
|
|
||||||
// 自定义规则
|
// 自定义规则
|
||||||
final JSONValueWriter valueWriter = GlobalValueWriters.get(value);
|
final ValueWriter valueWriter = ValueWriterManager.getInstance().get(value);
|
||||||
if(null != valueWriter){
|
if(null != valueWriter){
|
||||||
valueWriter.write(this, value);
|
valueWriter.write(this, value);
|
||||||
return this;
|
return this;
|
||||||
|
@ -21,17 +21,12 @@ import java.util.function.Predicate;
|
|||||||
/**
|
/**
|
||||||
* JSON的值自定义写出,通过自定义实现此接口,实现对象自定义写出字符串形式<br>
|
* JSON的值自定义写出,通过自定义实现此接口,实现对象自定义写出字符串形式<br>
|
||||||
* 如自定义的一个CustomBean,我只希望输出id的值,此时自定义此接口。<br>
|
* 如自定义的一个CustomBean,我只希望输出id的值,此时自定义此接口。<br>
|
||||||
* 其中{@link JSONValueWriter#test(Object)}负责判断何种对象使用此规则,{@link JSONValueWriter#write(JSONWriter, Object)}负责写出规则。
|
* 其中{@link ValueWriter#test(Object)}负责判断何种对象使用此规则,{@link ValueWriter#write(JSONWriter, Object)}负责写出规则。
|
||||||
*
|
|
||||||
* <p>
|
|
||||||
* 注意:使用{@link GlobalValueWriters#add(JSONValueWriter)}加入全局转换规则后,在JSON对象中,自定义对象不会被转换为JSON。
|
|
||||||
* 而是原始对象存在,只有在生成JSON字符串时才序列化。
|
|
||||||
* </p>
|
|
||||||
*
|
*
|
||||||
* @author looly
|
* @author looly
|
||||||
* @since 6.0.0
|
* @since 6.0.0
|
||||||
*/
|
*/
|
||||||
public interface JSONValueWriter extends Predicate<Object> {
|
public interface ValueWriter extends Predicate<Object> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 使用{@link JSONWriter} 写出对象
|
* 使用{@link JSONWriter} 写出对象
|
@ -0,0 +1,108 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2024 Hutool Team and hutool.cn
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.dromara.hutool.json.writer;
|
||||||
|
|
||||||
|
import org.dromara.hutool.core.lang.Assert;
|
||||||
|
import org.dromara.hutool.json.writer.impl.*;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ValueWriter管理器,用于管理ValueWriter,提供ValueWriter的注册和获取
|
||||||
|
*
|
||||||
|
* @author looly
|
||||||
|
* @since 5.8.0
|
||||||
|
*/
|
||||||
|
public class ValueWriterManager {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 类级的内部类,也就是静态的成员式内部类,该内部类的实例与外部类的实例 没有绑定关系,而且只有被调用到才会装载,从而实现了延迟加载
|
||||||
|
*/
|
||||||
|
private static class SingletonHolder {
|
||||||
|
/**
|
||||||
|
* 静态初始化器,由JVM来保证线程安全
|
||||||
|
*/
|
||||||
|
private static final ValueWriterManager INSTANCE;
|
||||||
|
static {
|
||||||
|
INSTANCE = new ValueWriterManager();
|
||||||
|
registerDefault();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获得单例的 ValueWriterManager
|
||||||
|
*
|
||||||
|
* @return ValueWriterManager
|
||||||
|
*/
|
||||||
|
public static ValueWriterManager getInstance() {
|
||||||
|
return ValueWriterManager.SingletonHolder.INSTANCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
private final List<ValueWriter> valueWriterList;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造
|
||||||
|
*/
|
||||||
|
public ValueWriterManager() {
|
||||||
|
this.valueWriterList = Collections.synchronizedList(new ArrayList<>(6));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加入自定义的对象值写出规则
|
||||||
|
*
|
||||||
|
* @param valueWriter 自定义对象写出实现
|
||||||
|
*/
|
||||||
|
public void register(final ValueWriter valueWriter) {
|
||||||
|
valueWriterList.add(Assert.notNull(valueWriter));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取自定义对象值写出规则,后加入的优先
|
||||||
|
*
|
||||||
|
* @param value 值,{@code null}表示需要自定义null的输出
|
||||||
|
* @return 自定义的 {@link ValueWriter}
|
||||||
|
*/
|
||||||
|
public ValueWriter get(final Object value) {
|
||||||
|
if (value instanceof ValueWriter) {
|
||||||
|
return (ValueWriter) value;
|
||||||
|
}
|
||||||
|
|
||||||
|
final List<ValueWriter> valueWriterList = this.valueWriterList;
|
||||||
|
ValueWriter valueWriter;
|
||||||
|
for (int i = valueWriterList.size() - 1 ; i >= 0 ; i--) {
|
||||||
|
valueWriter = valueWriterList.get(i);
|
||||||
|
if (valueWriter.test(value)) {
|
||||||
|
return valueWriter;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册默认的ValueWriter
|
||||||
|
*/
|
||||||
|
private static void registerDefault() {
|
||||||
|
final ValueWriterManager manager = SingletonHolder.INSTANCE;
|
||||||
|
// JDK对象最后判断
|
||||||
|
manager.register(JdkValueWriter.INSTANCE);
|
||||||
|
manager.register(NumberValueWriter.INSTANCE);
|
||||||
|
manager.register(DateValueWriter.INSTANCE);
|
||||||
|
manager.register(BooleanValueWriter.INSTANCE);
|
||||||
|
}
|
||||||
|
}
|
@ -14,7 +14,10 @@
|
|||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package org.dromara.hutool.json.writer;
|
package org.dromara.hutool.json.writer.impl;
|
||||||
|
|
||||||
|
import org.dromara.hutool.json.writer.JSONWriter;
|
||||||
|
import org.dromara.hutool.json.writer.ValueWriter;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Boolean类型的值写出器
|
* Boolean类型的值写出器
|
||||||
@ -22,7 +25,7 @@ package org.dromara.hutool.json.writer;
|
|||||||
* @author looly
|
* @author looly
|
||||||
* @since 6.0.0
|
* @since 6.0.0
|
||||||
*/
|
*/
|
||||||
public class BooleanValueWriter implements JSONValueWriter {
|
public class BooleanValueWriter implements ValueWriter {
|
||||||
/**
|
/**
|
||||||
* 单例对象
|
* 单例对象
|
||||||
*/
|
*/
|
@ -14,7 +14,7 @@
|
|||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package org.dromara.hutool.json.writer;
|
package org.dromara.hutool.json.writer.impl;
|
||||||
|
|
||||||
import org.dromara.hutool.core.convert.ConvertUtil;
|
import org.dromara.hutool.core.convert.ConvertUtil;
|
||||||
import org.dromara.hutool.core.date.DateUtil;
|
import org.dromara.hutool.core.date.DateUtil;
|
||||||
@ -22,6 +22,8 @@ import org.dromara.hutool.core.date.TemporalAccessorUtil;
|
|||||||
import org.dromara.hutool.core.date.format.GlobalCustomFormat;
|
import org.dromara.hutool.core.date.format.GlobalCustomFormat;
|
||||||
import org.dromara.hutool.core.text.StrUtil;
|
import org.dromara.hutool.core.text.StrUtil;
|
||||||
import org.dromara.hutool.json.InternalJSONUtil;
|
import org.dromara.hutool.json.InternalJSONUtil;
|
||||||
|
import org.dromara.hutool.json.writer.JSONWriter;
|
||||||
|
import org.dromara.hutool.json.writer.ValueWriter;
|
||||||
|
|
||||||
import java.time.MonthDay;
|
import java.time.MonthDay;
|
||||||
import java.time.temporal.TemporalAccessor;
|
import java.time.temporal.TemporalAccessor;
|
||||||
@ -35,7 +37,7 @@ import java.util.Date;
|
|||||||
* @author looly
|
* @author looly
|
||||||
* @since 6.0.0
|
* @since 6.0.0
|
||||||
*/
|
*/
|
||||||
public class DateValueWriter implements JSONValueWriter {
|
public class DateValueWriter implements ValueWriter {
|
||||||
/**
|
/**
|
||||||
* 单例对象
|
* 单例对象
|
||||||
*/
|
*/
|
@ -14,12 +14,17 @@
|
|||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package org.dromara.hutool.json.writer;
|
package org.dromara.hutool.json.writer.impl;
|
||||||
|
|
||||||
import org.dromara.hutool.core.array.ArrayUtil;
|
import org.dromara.hutool.core.array.ArrayUtil;
|
||||||
import org.dromara.hutool.core.reflect.ClassUtil;
|
import org.dromara.hutool.core.reflect.ClassUtil;
|
||||||
|
import org.dromara.hutool.json.writer.JSONWriter;
|
||||||
|
import org.dromara.hutool.json.writer.ValueWriter;
|
||||||
|
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
|
import java.time.temporal.TemporalAccessor;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
@ -38,7 +43,7 @@ import java.util.Optional;
|
|||||||
* @author looly
|
* @author looly
|
||||||
* @since 6.0.0
|
* @since 6.0.0
|
||||||
*/
|
*/
|
||||||
public class JdkValueWriter implements JSONValueWriter {
|
public class JdkValueWriter implements ValueWriter {
|
||||||
/**
|
/**
|
||||||
* 单例对象
|
* 单例对象
|
||||||
*/
|
*/
|
||||||
@ -53,8 +58,14 @@ public class JdkValueWriter implements JSONValueWriter {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 可转换为JSONObject和JSONArray的对象
|
// 自定义写出的跳过
|
||||||
if (value instanceof Map
|
if (value instanceof Number
|
||||||
|
|| value instanceof Date
|
||||||
|
|| value instanceof Calendar
|
||||||
|
|| value instanceof TemporalAccessor
|
||||||
|
|| value instanceof Boolean
|
||||||
|
// 可转换为JSONObject和JSONArray的对象
|
||||||
|
|| value instanceof Map
|
||||||
|| value instanceof Map.Entry
|
|| value instanceof Map.Entry
|
||||||
|| value instanceof Iterable
|
|| value instanceof Iterable
|
||||||
|| ArrayUtil.isArray(value)
|
|| ArrayUtil.isArray(value)
|
||||||
@ -69,6 +80,12 @@ public class JdkValueWriter implements JSONValueWriter {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void write(final JSONWriter writer, final Object value) {
|
public void write(final JSONWriter writer, final Object value) {
|
||||||
writer.writeQuoteStrValue(value.toString());
|
final String valueStr;
|
||||||
|
if(value instanceof Class<?>){
|
||||||
|
valueStr = ((Class<?>) value).getName();
|
||||||
|
}else{
|
||||||
|
valueStr = value.toString();
|
||||||
|
}
|
||||||
|
writer.writeQuoteStrValue(valueStr);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -14,11 +14,14 @@
|
|||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package org.dromara.hutool.json.writer;
|
package org.dromara.hutool.json.writer.impl;
|
||||||
|
|
||||||
import org.dromara.hutool.core.math.NumberUtil;
|
import org.dromara.hutool.core.math.NumberUtil;
|
||||||
import org.dromara.hutool.json.JSONConfig;
|
import org.dromara.hutool.json.JSONConfig;
|
||||||
import org.dromara.hutool.json.JSONException;
|
import org.dromara.hutool.json.JSONException;
|
||||||
|
import org.dromara.hutool.json.writer.JSONWriter;
|
||||||
|
import org.dromara.hutool.json.writer.NumberWriteMode;
|
||||||
|
import org.dromara.hutool.json.writer.ValueWriter;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 数字类型的值写出器
|
* 数字类型的值写出器
|
||||||
@ -26,7 +29,7 @@ import org.dromara.hutool.json.JSONException;
|
|||||||
* @author looly
|
* @author looly
|
||||||
* @since 6.0.0
|
* @since 6.0.0
|
||||||
*/
|
*/
|
||||||
public class NumberValueWriter implements JSONValueWriter {
|
public class NumberValueWriter implements ValueWriter {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* JS中表示的数字最大值
|
* JS中表示的数字最大值
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2013-2024 Hutool Team and hutool.cn
|
* Copyright (c) 2024 Hutool Team and hutool.cn
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -14,27 +14,9 @@
|
|||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package org.dromara.hutool.json.writer;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@link Class}类型的值写出器
|
* {@link org.dromara.hutool.json.writer.ValueWriter} 实现
|
||||||
*
|
*
|
||||||
* @author looly
|
* @author Looly
|
||||||
* @since 6.0.0
|
|
||||||
*/
|
*/
|
||||||
public class ClassValueWriter implements JSONValueWriter {
|
package org.dromara.hutool.json.writer.impl;
|
||||||
/**
|
|
||||||
* 单例对象
|
|
||||||
*/
|
|
||||||
public static final ClassValueWriter INSTANCE = new ClassValueWriter();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean test(final Object value) {
|
|
||||||
return value instanceof Class;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void write(final JSONWriter writer, final Object value) {
|
|
||||||
writer.writeQuoteStrValue(((Class<?>) value).getName());
|
|
||||||
}
|
|
||||||
}
|
|
@ -22,7 +22,7 @@ import org.dromara.hutool.core.text.StrUtil;
|
|||||||
import org.dromara.hutool.core.xml.XmlConstants;
|
import org.dromara.hutool.core.xml.XmlConstants;
|
||||||
import org.dromara.hutool.json.InternalJSONUtil;
|
import org.dromara.hutool.json.InternalJSONUtil;
|
||||||
import org.dromara.hutool.json.JSONException;
|
import org.dromara.hutool.json.JSONException;
|
||||||
import org.dromara.hutool.json.JSONObject;
|
import org.dromara.hutool.json.OldJSONObject;
|
||||||
|
|
||||||
import java.util.function.Predicate;
|
import java.util.function.Predicate;
|
||||||
|
|
||||||
@ -67,7 +67,7 @@ public class JSONXMLParser {
|
|||||||
* @param jo JSONObject
|
* @param jo JSONObject
|
||||||
* @throws JSONException 解析异常
|
* @throws JSONException 解析异常
|
||||||
*/
|
*/
|
||||||
public void parseJSONObject(final String xmlStr, final JSONObject jo) throws JSONException {
|
public void parseJSONObject(final String xmlStr, final OldJSONObject jo) throws JSONException {
|
||||||
final XMLTokener x = new XMLTokener(xmlStr);
|
final XMLTokener x = new XMLTokener(xmlStr);
|
||||||
while (x.more() && x.skipPast("<")) {
|
while (x.more() && x.skipPast("<")) {
|
||||||
parse(x, jo, null, 0);
|
parse(x, jo, null, 0);
|
||||||
@ -78,16 +78,16 @@ public class JSONXMLParser {
|
|||||||
* 扫描XML内容,并解析到JSONObject中。
|
* 扫描XML内容,并解析到JSONObject中。
|
||||||
*
|
*
|
||||||
* @param x {@link XMLTokener}
|
* @param x {@link XMLTokener}
|
||||||
* @param context {@link JSONObject}
|
* @param context {@link OldJSONObject}
|
||||||
* @param name 标签名,null表示从根标签开始解析
|
* @param name 标签名,null表示从根标签开始解析
|
||||||
* @param currentNestingDepth 当前层级
|
* @param currentNestingDepth 当前层级
|
||||||
* @return {@code true}表示解析完成
|
* @return {@code true}表示解析完成
|
||||||
* @throws JSONException JSON异常
|
* @throws JSONException JSON异常
|
||||||
*/
|
*/
|
||||||
private boolean parse(final XMLTokener x, final JSONObject context, final String name, final int currentNestingDepth) throws JSONException {
|
private boolean parse(final XMLTokener x, final OldJSONObject context, final String name, final int currentNestingDepth) throws JSONException {
|
||||||
final char c;
|
final char c;
|
||||||
int i;
|
int i;
|
||||||
final JSONObject jsonobject;
|
final OldJSONObject jsonobject;
|
||||||
String string;
|
String string;
|
||||||
final String tagName;
|
final String tagName;
|
||||||
Object token;
|
Object token;
|
||||||
@ -156,7 +156,7 @@ public class JSONXMLParser {
|
|||||||
} else {
|
} else {
|
||||||
tagName = (String) token;
|
tagName = (String) token;
|
||||||
token = null;
|
token = null;
|
||||||
jsonobject = new JSONObject();
|
jsonobject = new OldJSONObject();
|
||||||
final boolean keepStrings = parseConfig.isKeepStrings();
|
final boolean keepStrings = parseConfig.isKeepStrings();
|
||||||
for (; ; ) {
|
for (; ; ) {
|
||||||
if (token == null) {
|
if (token == null) {
|
||||||
|
@ -22,7 +22,7 @@ import org.dromara.hutool.core.text.escape.EscapeUtil;
|
|||||||
import org.dromara.hutool.core.text.StrUtil;
|
import org.dromara.hutool.core.text.StrUtil;
|
||||||
import org.dromara.hutool.json.JSONArray;
|
import org.dromara.hutool.json.JSONArray;
|
||||||
import org.dromara.hutool.json.JSONException;
|
import org.dromara.hutool.json.JSONException;
|
||||||
import org.dromara.hutool.json.JSONObject;
|
import org.dromara.hutool.json.OldJSONObject;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* JSON转XML字符串工具
|
* JSON转XML字符串工具
|
||||||
@ -70,13 +70,13 @@ public class JSONXMLSerializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final StringBuilder sb = new StringBuilder();
|
final StringBuilder sb = new StringBuilder();
|
||||||
if (object instanceof JSONObject) {
|
if (object instanceof OldJSONObject) {
|
||||||
|
|
||||||
// Emit <tagName>
|
// Emit <tagName>
|
||||||
appendTag(sb, tagName, false);
|
appendTag(sb, tagName, false);
|
||||||
|
|
||||||
// Loop thru the keys.
|
// Loop thru the keys.
|
||||||
((JSONObject) object).forEach((key, value) -> {
|
((OldJSONObject) object).forEach((key, value) -> {
|
||||||
if (ArrayUtil.isArray(value)) {
|
if (ArrayUtil.isArray(value)) {
|
||||||
value = new JSONArray(value);
|
value = new JSONArray(value);
|
||||||
}
|
}
|
||||||
|
@ -17,7 +17,7 @@
|
|||||||
package org.dromara.hutool.json.xml;
|
package org.dromara.hutool.json.xml;
|
||||||
|
|
||||||
import org.dromara.hutool.json.JSONException;
|
import org.dromara.hutool.json.JSONException;
|
||||||
import org.dromara.hutool.json.JSONObject;
|
import org.dromara.hutool.json.OldJSONObject;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 提供静态方法在XML和JSONObject之间转换
|
* 提供静态方法在XML和JSONObject之间转换
|
||||||
@ -37,7 +37,7 @@ public class JSONXMLUtil {
|
|||||||
* @return A JSONObject containing the structured data from the XML string.
|
* @return A JSONObject containing the structured data from the XML string.
|
||||||
* @throws JSONException Thrown if there is an errors while parsing the string
|
* @throws JSONException Thrown if there is an errors while parsing the string
|
||||||
*/
|
*/
|
||||||
public static JSONObject toJSONObject(final String string) throws JSONException {
|
public static OldJSONObject toJSONObject(final String string) throws JSONException {
|
||||||
return toJSONObject(string, ParseConfig.of());
|
return toJSONObject(string, ParseConfig.of());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -52,8 +52,8 @@ public class JSONXMLUtil {
|
|||||||
* @return A JSONObject containing the structured data from the XML string.
|
* @return A JSONObject containing the structured data from the XML string.
|
||||||
* @throws JSONException Thrown if there is an errors while parsing the string
|
* @throws JSONException Thrown if there is an errors while parsing the string
|
||||||
*/
|
*/
|
||||||
public static JSONObject toJSONObject(final String string, final ParseConfig parseConfig) throws JSONException {
|
public static OldJSONObject toJSONObject(final String string, final ParseConfig parseConfig) throws JSONException {
|
||||||
return toJSONObject(string, new JSONObject(), parseConfig);
|
return toJSONObject(string, new OldJSONObject(), parseConfig);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -67,7 +67,7 @@ public class JSONXMLUtil {
|
|||||||
* @throws JSONException 解析异常
|
* @throws JSONException 解析异常
|
||||||
* @since 5.3.1
|
* @since 5.3.1
|
||||||
*/
|
*/
|
||||||
public static JSONObject toJSONObject(final String xmlStr, final JSONObject jo, final ParseConfig parseConfig) throws JSONException {
|
public static OldJSONObject toJSONObject(final String xmlStr, final OldJSONObject jo, final ParseConfig parseConfig) throws JSONException {
|
||||||
JSONXMLParser.of(parseConfig, null).parseJSONObject(xmlStr, jo);
|
JSONXMLParser.of(parseConfig, null).parseJSONObject(xmlStr, jo);
|
||||||
return jo;
|
return jo;
|
||||||
}
|
}
|
||||||
|
@ -32,7 +32,7 @@ public class CustomSerializeTest {
|
|||||||
public void init() {
|
public void init() {
|
||||||
SerializerManager.getInstance().register(CustomBean.class,
|
SerializerManager.getInstance().register(CustomBean.class,
|
||||||
(JSONSerializer<CustomBean>) (bean, context) ->
|
(JSONSerializer<CustomBean>) (bean, context) ->
|
||||||
((JSONObject)context.getContextJson()).set("customName", bean.name));
|
((OldJSONObject)context.getContextJson()).set("customName", bean.name));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -40,7 +40,7 @@ public class CustomSerializeTest {
|
|||||||
final CustomBean customBean = new CustomBean();
|
final CustomBean customBean = new CustomBean();
|
||||||
customBean.name = "testName";
|
customBean.name = "testName";
|
||||||
|
|
||||||
final JSONObject obj = JSONUtil.parseObj(customBean);
|
final OldJSONObject obj = JSONUtil.parseObj(customBean);
|
||||||
Assertions.assertEquals("testName", obj.getStr("customName"));
|
Assertions.assertEquals("testName", obj.getStr("customName"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -49,7 +49,7 @@ public class CustomSerializeTest {
|
|||||||
final CustomBean customBean = new CustomBean();
|
final CustomBean customBean = new CustomBean();
|
||||||
customBean.name = "testName";
|
customBean.name = "testName";
|
||||||
|
|
||||||
final JSONObject obj = JSONUtil.ofObj().set("customBean", customBean);
|
final OldJSONObject obj = JSONUtil.ofObj().set("customBean", customBean);
|
||||||
Assertions.assertEquals("testName", obj.getJSONObject("customBean").getStr("customName"));
|
Assertions.assertEquals("testName", obj.getJSONObject("customBean").getStr("customName"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -57,7 +57,7 @@ public class CustomSerializeTest {
|
|||||||
public void deserializeTest() {
|
public void deserializeTest() {
|
||||||
SerializerManager.getInstance().register(CustomBean.class, (JSONDeserializer<CustomBean>) (json, deserializeType) -> {
|
SerializerManager.getInstance().register(CustomBean.class, (JSONDeserializer<CustomBean>) (json, deserializeType) -> {
|
||||||
final CustomBean customBean = new CustomBean();
|
final CustomBean customBean = new CustomBean();
|
||||||
customBean.name = ((JSONObject) json).getStr("customName");
|
customBean.name = ((OldJSONObject) json).getStr("customName");
|
||||||
return customBean;
|
return customBean;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -71,7 +71,7 @@ public class Issue1101Test {
|
|||||||
"\t\"type\": 0\n" +
|
"\t\"type\": 0\n" +
|
||||||
"}";
|
"}";
|
||||||
|
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(json);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(json);
|
||||||
|
|
||||||
final TreeNode treeNode = JSONUtil.toBean(jsonObject, TreeNode.class);
|
final TreeNode treeNode = JSONUtil.toBean(jsonObject, TreeNode.class);
|
||||||
Assertions.assertEquals(2, treeNode.getChildren().size());
|
Assertions.assertEquals(2, treeNode.getChildren().size());
|
||||||
|
@ -30,7 +30,7 @@ public class Issue1200Test {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void toBeanTest() {
|
public void toBeanTest() {
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(
|
final OldJSONObject jsonObject = JSONUtil.parseObj(
|
||||||
ResourceUtil.readUtf8Str("issue1200.json"),
|
ResourceUtil.readUtf8Str("issue1200.json"),
|
||||||
JSONConfig.of().setIgnoreError(true));
|
JSONConfig.of().setIgnoreError(true));
|
||||||
|
|
||||||
|
@ -28,7 +28,7 @@ import java.sql.SQLException;
|
|||||||
public class Issue1399Test {
|
public class Issue1399Test {
|
||||||
@Test
|
@Test
|
||||||
void sqlExceptionTest() {
|
void sqlExceptionTest() {
|
||||||
final JSONObject set = JSONUtil.ofObj().set("error", new SQLException("test"));
|
final OldJSONObject set = JSONUtil.ofObj().set("error", new SQLException("test"));
|
||||||
Assertions.assertEquals("{\"error\":\"java.sql.SQLException: test\"}", set.toString());
|
Assertions.assertEquals("{\"error\":\"java.sql.SQLException: test\"}", set.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -35,7 +35,7 @@ public class Issue2090Test {
|
|||||||
final TestBean test = new TestBean();
|
final TestBean test = new TestBean();
|
||||||
test.setLocalDate(LocalDate.now());
|
test.setLocalDate(LocalDate.now());
|
||||||
|
|
||||||
final JSONObject json = JSONUtil.parseObj(test);
|
final OldJSONObject json = JSONUtil.parseObj(test);
|
||||||
final TestBean test1 = json.toBean(TestBean.class);
|
final TestBean test1 = json.toBean(TestBean.class);
|
||||||
Assertions.assertEquals(test, test1);
|
Assertions.assertEquals(test, test1);
|
||||||
}
|
}
|
||||||
@ -43,14 +43,14 @@ public class Issue2090Test {
|
|||||||
@Test
|
@Test
|
||||||
public void parseLocalDateTest(){
|
public void parseLocalDateTest(){
|
||||||
final LocalDate localDate = LocalDate.now();
|
final LocalDate localDate = LocalDate.now();
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(localDate);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(localDate);
|
||||||
Assertions.assertNotNull(jsonObject.toString());
|
Assertions.assertNotNull(jsonObject.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void toBeanLocalDateTest(){
|
public void toBeanLocalDateTest(){
|
||||||
final LocalDate d = LocalDate.now();
|
final LocalDate d = LocalDate.now();
|
||||||
final JSONObject obj = JSONUtil.parseObj(d);
|
final OldJSONObject obj = JSONUtil.parseObj(d);
|
||||||
final LocalDate d2 = obj.toBean(LocalDate.class);
|
final LocalDate d2 = obj.toBean(LocalDate.class);
|
||||||
Assertions.assertEquals(d, d2);
|
Assertions.assertEquals(d, d2);
|
||||||
}
|
}
|
||||||
@ -58,7 +58,7 @@ public class Issue2090Test {
|
|||||||
@Test
|
@Test
|
||||||
public void toBeanLocalDateTimeTest(){
|
public void toBeanLocalDateTimeTest(){
|
||||||
final LocalDateTime d = LocalDateTime.now();
|
final LocalDateTime d = LocalDateTime.now();
|
||||||
final JSONObject obj = JSONUtil.parseObj(d);
|
final OldJSONObject obj = JSONUtil.parseObj(d);
|
||||||
final LocalDateTime d2 = obj.toBean(LocalDateTime.class);
|
final LocalDateTime d2 = obj.toBean(LocalDateTime.class);
|
||||||
Assertions.assertEquals(d, d2);
|
Assertions.assertEquals(d, d2);
|
||||||
}
|
}
|
||||||
@ -66,14 +66,14 @@ public class Issue2090Test {
|
|||||||
@Test
|
@Test
|
||||||
public void toBeanLocalTimeTest(){
|
public void toBeanLocalTimeTest(){
|
||||||
final LocalTime d = LocalTime.now();
|
final LocalTime d = LocalTime.now();
|
||||||
final JSONObject obj = JSONUtil.parseObj(d);
|
final OldJSONObject obj = JSONUtil.parseObj(d);
|
||||||
final LocalTime d2 = obj.toBean(LocalTime.class);
|
final LocalTime d2 = obj.toBean(LocalTime.class);
|
||||||
Assertions.assertEquals(d, d2);
|
Assertions.assertEquals(d, d2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void monthTest(){
|
public void monthTest(){
|
||||||
final JSONObject jsonObject = new JSONObject();
|
final OldJSONObject jsonObject = new OldJSONObject();
|
||||||
jsonObject.set("month", Month.JANUARY);
|
jsonObject.set("month", Month.JANUARY);
|
||||||
Assertions.assertEquals("{\"month\":1}", jsonObject.toString());
|
Assertions.assertEquals("{\"month\":1}", jsonObject.toString());
|
||||||
}
|
}
|
||||||
|
@ -42,7 +42,7 @@ public class Issue2131Test {
|
|||||||
Stream.of(apple, pear).forEach(collections::add);
|
Stream.of(apple, pear).forEach(collections::add);
|
||||||
|
|
||||||
final String jsonStr = JSONUtil.toJsonStr(goodsResponse);
|
final String jsonStr = JSONUtil.toJsonStr(goodsResponse);
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(jsonStr);
|
||||||
|
|
||||||
final GoodsResponse result = jsonObject.toBean(GoodsResponse.class);
|
final GoodsResponse result = jsonObject.toBean(GoodsResponse.class);
|
||||||
Assertions.assertEquals(0, result.getCollections().size());
|
Assertions.assertEquals(0, result.getCollections().size());
|
||||||
|
@ -16,18 +16,18 @@
|
|||||||
|
|
||||||
package org.dromara.hutool.json;
|
package org.dromara.hutool.json;
|
||||||
|
|
||||||
import org.dromara.hutool.core.lang.Console;
|
|
||||||
import org.junit.jupiter.api.Disabled;
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
public class Issue2507Test {
|
public class Issue2507Test {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@Disabled
|
|
||||||
public void xmlToJsonTest(){
|
public void xmlToJsonTest(){
|
||||||
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 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>";
|
||||||
JSONObject jsonObject = JSONUtil.xmlToJson(xml);
|
final OldJSONObject jsonObject = JSONUtil.xmlToJson(xml);
|
||||||
|
|
||||||
Console.log(jsonObject.toStringPretty());
|
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -57,7 +57,7 @@ public class Issue2555Test {
|
|||||||
public static class MySerializer implements JSONSerializer<MyType> {
|
public static class MySerializer implements JSONSerializer<MyType> {
|
||||||
@Override
|
@Override
|
||||||
public JSON serialize(final MyType bean, final JSONContext context) {
|
public JSON serialize(final MyType bean, final JSONContext context) {
|
||||||
return ((JSONObject)context.getContextJson()).set("addr", bean.getAddress());
|
return ((OldJSONObject)context.getContextJson()).set("addr", bean.getAddress());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -65,7 +65,7 @@ public class Issue2555Test {
|
|||||||
@Override
|
@Override
|
||||||
public MyType deserialize(final JSON json, final Type deserializeType) {
|
public MyType deserialize(final JSON json, final Type deserializeType) {
|
||||||
final MyType myType = new MyType();
|
final MyType myType = new MyType();
|
||||||
myType.setAddress(((JSONObject)json).getStr("addr"));
|
myType.setAddress(((OldJSONObject)json).getStr("addr"));
|
||||||
return myType;
|
return myType;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -32,7 +32,7 @@ public class Issue2572Test {
|
|||||||
public void putDayOfWeekTest(){
|
public void putDayOfWeekTest(){
|
||||||
final Set<DayOfWeek> weeks = new HashSet<>();
|
final Set<DayOfWeek> weeks = new HashSet<>();
|
||||||
weeks.add(DayOfWeek.MONDAY);
|
weeks.add(DayOfWeek.MONDAY);
|
||||||
final JSONObject obj = new JSONObject();
|
final OldJSONObject obj = new OldJSONObject();
|
||||||
obj.set("weeks", weeks);
|
obj.set("weeks", weeks);
|
||||||
Assertions.assertEquals("{\"weeks\":[1]}", obj.toString());
|
Assertions.assertEquals("{\"weeks\":[1]}", obj.toString());
|
||||||
|
|
||||||
@ -45,7 +45,7 @@ public class Issue2572Test {
|
|||||||
public void putMonthTest(){
|
public void putMonthTest(){
|
||||||
final Set<Month> months = new HashSet<>();
|
final Set<Month> months = new HashSet<>();
|
||||||
months.add(Month.DECEMBER);
|
months.add(Month.DECEMBER);
|
||||||
final JSONObject obj = new JSONObject();
|
final OldJSONObject obj = new OldJSONObject();
|
||||||
obj.set("months", months);
|
obj.set("months", months);
|
||||||
Assertions.assertEquals("{\"months\":[12]}", obj.toString());
|
Assertions.assertEquals("{\"months\":[12]}", obj.toString());
|
||||||
|
|
||||||
@ -58,7 +58,7 @@ public class Issue2572Test {
|
|||||||
public void putMonthDayTest(){
|
public void putMonthDayTest(){
|
||||||
final Set<MonthDay> monthDays = new HashSet<>();
|
final Set<MonthDay> monthDays = new HashSet<>();
|
||||||
monthDays.add(MonthDay.of(Month.DECEMBER, 1));
|
monthDays.add(MonthDay.of(Month.DECEMBER, 1));
|
||||||
final JSONObject obj = new JSONObject();
|
final OldJSONObject obj = new OldJSONObject();
|
||||||
obj.set("monthDays", monthDays);
|
obj.set("monthDays", monthDays);
|
||||||
Assertions.assertEquals("{\"monthDays\":[\"--12-01\"]}", obj.toString());
|
Assertions.assertEquals("{\"monthDays\":[\"--12-01\"]}", obj.toString());
|
||||||
|
|
||||||
|
@ -43,7 +43,7 @@ public class Issue2749Test {
|
|||||||
final String jsonStr = JSONUtil.toJsonStr(map);
|
final String jsonStr = JSONUtil.toJsonStr(map);
|
||||||
|
|
||||||
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
|
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
|
||||||
final JSONObject jsonObject = new JSONObject(jsonStr);
|
final OldJSONObject jsonObject = new OldJSONObject(jsonStr);
|
||||||
Assertions.assertNotNull(jsonObject);
|
Assertions.assertNotNull(jsonObject);
|
||||||
|
|
||||||
// 栈溢出
|
// 栈溢出
|
||||||
|
@ -22,7 +22,7 @@ import org.junit.jupiter.api.Test;
|
|||||||
public class Issue2801Test {
|
public class Issue2801Test {
|
||||||
@Test
|
@Test
|
||||||
public void toStringTest() {
|
public void toStringTest() {
|
||||||
final JSONObject recordObj = new JSONObject(JSONConfig.of().setIgnoreNullValue(false));
|
final OldJSONObject recordObj = new OldJSONObject(JSONConfig.of().setIgnoreNullValue(false));
|
||||||
recordObj.put("m_reportId", null);
|
recordObj.put("m_reportId", null);
|
||||||
Assertions.assertEquals("{\"m_reportId\":null}", recordObj.toString());
|
Assertions.assertEquals("{\"m_reportId\":null}", recordObj.toString());
|
||||||
}
|
}
|
||||||
|
@ -23,7 +23,7 @@ public class Issue2953Test {
|
|||||||
@Test
|
@Test
|
||||||
public void parseObjWithBigNumberTest() {
|
public void parseObjWithBigNumberTest() {
|
||||||
final String a = "{\"a\": 114793903847679990000000000000000000000}";
|
final String a = "{\"a\": 114793903847679990000000000000000000000}";
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(a, JSONConfig.of());
|
final OldJSONObject jsonObject = JSONUtil.parseObj(a, JSONConfig.of());
|
||||||
Assertions.assertEquals("{\"a\":\"114793903847679990000000000000000000000\"}", jsonObject.toString());
|
Assertions.assertEquals("{\"a\":\"114793903847679990000000000000000000000\"}", jsonObject.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -24,7 +24,7 @@ public class Issue3051Test {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void parseTest() {
|
public void parseTest() {
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(new EmptyBean(),
|
final OldJSONObject jsonObject = JSONUtil.parseObj(new EmptyBean(),
|
||||||
JSONConfig.of().setIgnoreError(true));
|
JSONConfig.of().setIgnoreError(true));
|
||||||
|
|
||||||
Assertions.assertEquals("{}", jsonObject.toString());
|
Assertions.assertEquals("{}", jsonObject.toString());
|
||||||
@ -33,7 +33,7 @@ public class Issue3051Test {
|
|||||||
@Test
|
@Test
|
||||||
public void parseTest2() {
|
public void parseTest2() {
|
||||||
Assertions.assertThrows(JSONException.class, ()->{
|
Assertions.assertThrows(JSONException.class, ()->{
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(new EmptyBean());
|
final OldJSONObject jsonObject = JSONUtil.parseObj(new EmptyBean());
|
||||||
Assertions.assertEquals("{}", jsonObject.toString());
|
Assertions.assertEquals("{}", jsonObject.toString());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -70,9 +70,9 @@ public class Issue3086Test {
|
|||||||
public JSON serialize(final TestBean bean, final JSONContext context) {
|
public JSON serialize(final TestBean bean, final JSONContext context) {
|
||||||
final List<String> strings = bean.getAuthorities()
|
final List<String> strings = bean.getAuthorities()
|
||||||
.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.toList());
|
.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.toList());
|
||||||
JSONObject contextJson = (JSONObject) context.getContextJson();
|
OldJSONObject contextJson = (OldJSONObject) context.getContextJson();
|
||||||
if(null == contextJson){
|
if(null == contextJson){
|
||||||
contextJson = new JSONObject(context.config());
|
contextJson = new OldJSONObject(context.config());
|
||||||
}
|
}
|
||||||
contextJson.set("authorities",strings);
|
contextJson.set("authorities",strings);
|
||||||
return contextJson;
|
return contextJson;
|
||||||
|
@ -33,7 +33,7 @@ public class Issue3139Test {
|
|||||||
" </c>\n" +
|
" </c>\n" +
|
||||||
"</r>";
|
"</r>";
|
||||||
|
|
||||||
final JSONObject jsonObject = XmlUtil.xmlToBean(XmlUtil.parseXml(xml).getDocumentElement(), JSONObject.class);
|
final OldJSONObject jsonObject = XmlUtil.xmlToBean(XmlUtil.parseXml(xml).getDocumentElement(), OldJSONObject.class);
|
||||||
final R bean = jsonObject.toBean(R.class);
|
final R bean = jsonObject.toBean(R.class);
|
||||||
Assertions.assertNotNull(bean);
|
Assertions.assertNotNull(bean);
|
||||||
|
|
||||||
|
@ -23,7 +23,7 @@ public class Issue3193Test {
|
|||||||
@Test
|
@Test
|
||||||
void parseTest() {
|
void parseTest() {
|
||||||
final String jsonStr = "{\"desc\":\"测试数据\\\\\"}";
|
final String jsonStr = "{\"desc\":\"测试数据\\\\\"}";
|
||||||
final JSONObject parse = JSONUtil.parseObj(jsonStr);
|
final OldJSONObject parse = JSONUtil.parseObj(jsonStr);
|
||||||
Assertions.assertEquals("测试数据\\", parse.getStr("desc"));
|
Assertions.assertEquals("测试数据\\", parse.getStr("desc"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -24,7 +24,7 @@ import org.junit.jupiter.api.Test;
|
|||||||
public class Issue3274Test {
|
public class Issue3274Test {
|
||||||
@Test
|
@Test
|
||||||
public void toBeanTest() {
|
public void toBeanTest() {
|
||||||
final JSONObject entries = new JSONObject("{\n" +
|
final OldJSONObject entries = new OldJSONObject("{\n" +
|
||||||
" \n" +
|
" \n" +
|
||||||
" \"age\": 36,\n" +
|
" \"age\": 36,\n" +
|
||||||
" \"gender\": \"\",\n" +
|
" \"gender\": \"\",\n" +
|
||||||
|
@ -24,7 +24,7 @@ public class Issue3619Test {
|
|||||||
public void parseObjTest() {
|
public void parseObjTest() {
|
||||||
final String json = "{\"@timestamp\":\"2024-06-14T00:02:06.438Z\",\"@version\":\"1\",\"int_arr\":[-4]}";
|
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 JSONConfig jsonConfig = JSONConfig.of().setKeyComparator(String.CASE_INSENSITIVE_ORDER);
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(json, jsonConfig);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(json, jsonConfig);
|
||||||
|
|
||||||
final String jsonStr = jsonObject.toJSONString(0, pair -> {
|
final String jsonStr = jsonObject.toJSONString(0, pair -> {
|
||||||
final Object key = pair.getKey();
|
final Object key = pair.getKey();
|
||||||
|
@ -33,7 +33,7 @@ public class Issue644Test {
|
|||||||
final BeanWithDate beanWithDate = new BeanWithDate();
|
final BeanWithDate beanWithDate = new BeanWithDate();
|
||||||
beanWithDate.setDate(LocalDateTime.now());
|
beanWithDate.setDate(LocalDateTime.now());
|
||||||
|
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(beanWithDate);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(beanWithDate);
|
||||||
|
|
||||||
BeanWithDate beanWithDate2 = JSONUtil.toBean(jsonObject, BeanWithDate.class);
|
BeanWithDate beanWithDate2 = JSONUtil.toBean(jsonObject, BeanWithDate.class);
|
||||||
Assertions.assertEquals(TimeUtil.formatNormal(beanWithDate.getDate()),
|
Assertions.assertEquals(TimeUtil.formatNormal(beanWithDate.getDate()),
|
||||||
|
@ -25,7 +25,7 @@ public class IssueI3EGJPTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void hutoolMapToBean() {
|
public void hutoolMapToBean() {
|
||||||
final JSONObject paramJson = new JSONObject();
|
final OldJSONObject paramJson = new OldJSONObject();
|
||||||
paramJson.set("is_booleana", "1");
|
paramJson.set("is_booleana", "1");
|
||||||
paramJson.set("is_booleanb", true);
|
paramJson.set("is_booleanb", true);
|
||||||
final ConvertDO convertDO = BeanUtil.toBean(paramJson, ConvertDO.class);
|
final ConvertDO convertDO = BeanUtil.toBean(paramJson, ConvertDO.class);
|
||||||
|
@ -28,7 +28,7 @@ public class IssueI4RBZ4Test {
|
|||||||
public void sortTest(){
|
public void sortTest(){
|
||||||
final String jsonStr = "{\"id\":\"123\",\"array\":[1,2,3],\"outNum\":356,\"body\":{\"ava1\":\"20220108\",\"use\":1,\"ava2\":\"20230108\"},\"name\":\"John\"}";
|
final String jsonStr = "{\"id\":\"123\",\"array\":[1,2,3],\"outNum\":356,\"body\":{\"ava1\":\"20220108\",\"use\":1,\"ava2\":\"20230108\"},\"name\":\"John\"}";
|
||||||
|
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(jsonStr, JSONConfig.of().setNatureKeyComparator());
|
final OldJSONObject 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());
|
Assertions.assertEquals("{\"array\":[1,2,3],\"body\":{\"ava1\":\"20220108\",\"ava2\":\"20230108\",\"use\":1},\"id\":\"123\",\"name\":\"John\",\"outNum\":356}", jsonObject.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -22,7 +22,7 @@ import org.junit.jupiter.api.Test;
|
|||||||
public class IssueI59LW4Test {
|
public class IssueI59LW4Test {
|
||||||
@Test
|
@Test
|
||||||
public void bytesTest(){
|
public void bytesTest(){
|
||||||
final JSONObject jsonObject = JSONUtil.ofObj().set("bytes", new byte[]{1});
|
final OldJSONObject jsonObject = JSONUtil.ofObj().set("bytes", new byte[]{1});
|
||||||
Assertions.assertEquals("{\"bytes\":[1]}", jsonObject.toString());
|
Assertions.assertEquals("{\"bytes\":[1]}", jsonObject.toString());
|
||||||
|
|
||||||
final byte[] bytes = jsonObject.getBytes("bytes");
|
final byte[] bytes = jsonObject.getBytes("bytes");
|
||||||
|
@ -34,7 +34,7 @@ public class IssueI5DHK2Test {
|
|||||||
" }]\n" +
|
" }]\n" +
|
||||||
"}";
|
"}";
|
||||||
|
|
||||||
final JSONObject json = JSONUtil.parseObj(jsonStr);
|
final OldJSONObject json = JSONUtil.parseObj(jsonStr);
|
||||||
final String exployerName = json
|
final String exployerName = json
|
||||||
.getJSONArray("punished_parties")
|
.getJSONArray("punished_parties")
|
||||||
.getJSONObject(0)
|
.getJSONObject(0)
|
||||||
|
@ -28,7 +28,7 @@ public class IssueI5OMSCTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void filterTest(){
|
public void filterTest(){
|
||||||
final JSONObject json = JSONUtil.parseObj(ResourceUtil.readUtf8Str("issueI5OMSC.json"));
|
final OldJSONObject json = JSONUtil.parseObj(ResourceUtil.readUtf8Str("issueI5OMSC.json"));
|
||||||
|
|
||||||
final String s = json.toJSONString(0, (entry) -> {
|
final String s = json.toJSONString(0, (entry) -> {
|
||||||
final Object key = entry.getKey();
|
final Object key = entry.getKey();
|
||||||
|
@ -28,7 +28,7 @@ import javax.xml.xpath.XPathConstants;
|
|||||||
public class IssueI676ITTest {
|
public class IssueI676ITTest {
|
||||||
@Test
|
@Test
|
||||||
public void parseXMLTest() {
|
public void parseXMLTest() {
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(ResourceUtil.readUtf8Str("issueI676IT.json"));
|
final OldJSONObject jsonObject = JSONUtil.parseObj(ResourceUtil.readUtf8Str("issueI676IT.json"));
|
||||||
final String xmlStr = JSONXMLSerializer.toXml(jsonObject, null, (String) null);
|
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));
|
final String content = String.valueOf(XPathUtil.getByXPath("/page/orderItems[1]/content", XmlUtil.readXml(xmlStr), XPathConstants.STRING));
|
||||||
Assertions.assertEquals(content, "bar1");
|
Assertions.assertEquals(content, "bar1");
|
||||||
|
@ -30,7 +30,7 @@ public class IssueI6YN2ATest {
|
|||||||
public void toBeanTest() {
|
public void toBeanTest() {
|
||||||
final String str = "{\"conditions\":{\"user\":\"test\",\"sex\":\"男\"}," +
|
final String str = "{\"conditions\":{\"user\":\"test\",\"sex\":\"男\"}," +
|
||||||
"\"headers\":{\"name\":\"姓名\",\"age\":\"年龄\",\"email\":\"邮箱\",\"number\":\"号码\",\"pwd\":\"密码\"}}";
|
"\"headers\":{\"name\":\"姓名\",\"age\":\"年龄\",\"email\":\"邮箱\",\"number\":\"号码\",\"pwd\":\"密码\"}}";
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(str);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(str);
|
||||||
|
|
||||||
final PageQuery<User> bean = jsonObject.toBean(new TypeReference<PageQuery<User>>() {});
|
final PageQuery<User> bean = jsonObject.toBean(new TypeReference<PageQuery<User>>() {});
|
||||||
Assertions.assertEquals("{name=姓名, age=年龄, email=邮箱, number=号码, pwd=密码}", bean.headers.toString());
|
Assertions.assertEquals("{name=姓名, age=年龄, email=邮箱, number=号码, pwd=密码}", bean.headers.toString());
|
||||||
|
@ -26,7 +26,7 @@ public class IssueI76CSUTest {
|
|||||||
@Test
|
@Test
|
||||||
void parseTest() {
|
void parseTest() {
|
||||||
final String str = "{ \"card\": true, \"content\": \"【标题】\n摘要\", \"time\": 1678434181000}";
|
final String str = "{ \"card\": true, \"content\": \"【标题】\n摘要\", \"time\": 1678434181000}";
|
||||||
final JSONObject entries = JSONUtil.parseObj(str);
|
final OldJSONObject entries = JSONUtil.parseObj(str);
|
||||||
Assertions.assertEquals("【标题】\n摘要", entries.getStr("content"));
|
Assertions.assertEquals("【标题】\n摘要", entries.getStr("content"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -33,7 +33,7 @@ public class IssueI7VM64Test {
|
|||||||
final HashMap<String, Object> map = new HashMap<>();
|
final HashMap<String, Object> map = new HashMap<>();
|
||||||
map.put("a", "1");
|
map.put("a", "1");
|
||||||
|
|
||||||
final JSONObject jsonObject = new JSONObject();
|
final OldJSONObject jsonObject = new OldJSONObject();
|
||||||
jsonObject.put("c", map);
|
jsonObject.put("c", map);
|
||||||
map.put("b", 2);
|
map.put("b", 2);
|
||||||
|
|
||||||
|
@ -30,7 +30,7 @@ public class IssueI90ADXTest {
|
|||||||
final TestBean testBean = new TestBean();
|
final TestBean testBean = new TestBean();
|
||||||
testBean.name = "aaaa";
|
testBean.name = "aaaa";
|
||||||
|
|
||||||
final JSONObject json = JSONUtil.parseObj(testBean);
|
final OldJSONObject json = JSONUtil.parseObj(testBean);
|
||||||
Assertions.assertEquals("{\"name\":\"aaaa\"}", json.toString());
|
Assertions.assertEquals("{\"name\":\"aaaa\"}", json.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -26,7 +26,7 @@ public class IssueI9DX5HTest {
|
|||||||
@Test
|
@Test
|
||||||
void xmlToJSONTest() {
|
void xmlToJSONTest() {
|
||||||
final String xml = "<GoodMsg>你好</GoodMsg>";
|
final String xml = "<GoodMsg>你好</GoodMsg>";
|
||||||
final JSONObject jsonObject = new JSONObject(xml, JSONConfig.of(), entry -> {
|
final OldJSONObject jsonObject = new OldJSONObject(xml, JSONConfig.of(), entry -> {
|
||||||
entry.setKey(StrUtil.toUnderlineCase((CharSequence) entry.getKey()));
|
entry.setKey(StrUtil.toUnderlineCase((CharSequence) entry.getKey()));
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
|
@ -31,7 +31,7 @@ public class IssueI9HQQETest {
|
|||||||
final JSONConfig jsonConfig = new JSONConfig();
|
final JSONConfig jsonConfig = new JSONConfig();
|
||||||
jsonConfig.setDateFormat("dd/MM/yyyy");
|
jsonConfig.setDateFormat("dd/MM/yyyy");
|
||||||
|
|
||||||
final JSONObject entries = JSONUtil.parseObj(json, jsonConfig);
|
final OldJSONObject entries = JSONUtil.parseObj(json, jsonConfig);
|
||||||
|
|
||||||
final MMHBo mmh = entries.toBean(MMHBo.class);
|
final MMHBo mmh = entries.toBean(MMHBo.class);
|
||||||
Assertions.assertNotNull(mmh.getCurrentDate());
|
Assertions.assertNotNull(mmh.getCurrentDate());
|
||||||
|
@ -23,7 +23,7 @@ public class IssueIAP4GMTest {
|
|||||||
@Test
|
@Test
|
||||||
void parse() {
|
void parse() {
|
||||||
final String res = "{\"uid\":\"asdf\\n\"}";
|
final String res = "{\"uid\":\"asdf\\n\"}";
|
||||||
final JSONObject entries = JSONUtil.parseObj(res);
|
final OldJSONObject entries = JSONUtil.parseObj(res);
|
||||||
Assertions.assertEquals("asdf\n", entries.getStr("uid"));
|
Assertions.assertEquals("asdf\n", entries.getStr("uid"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -33,7 +33,7 @@ public class IssuesI44E4HTest {
|
|||||||
public void deserializerTest(){
|
public void deserializerTest(){
|
||||||
SerializerManager.getInstance().register(TestDto.class, (JSONDeserializer<TestDto>) (json, deserializeType) -> {
|
SerializerManager.getInstance().register(TestDto.class, (JSONDeserializer<TestDto>) (json, deserializeType) -> {
|
||||||
final TestDto testDto = new TestDto();
|
final TestDto testDto = new TestDto();
|
||||||
testDto.setMd(new AcBizModuleMd("name1", ((JSONObject)json).getStr("md")));
|
testDto.setMd(new AcBizModuleMd("name1", ((OldJSONObject)json).getStr("md")));
|
||||||
return testDto;
|
return testDto;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -27,7 +27,7 @@ public class IssuesI4V14NTest {
|
|||||||
@Test
|
@Test
|
||||||
public void parseTest(){
|
public void parseTest(){
|
||||||
final String str = "{\"A\" : \"A\\nb\"}";
|
final String str = "{\"A\" : \"A\\nb\"}";
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(str);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(str);
|
||||||
Assertions.assertEquals("A\nb", jsonObject.getStr("A"));
|
Assertions.assertEquals("A\nb", jsonObject.getStr("A"));
|
||||||
|
|
||||||
final Map<String, String> map = jsonObject.toBean(new TypeReference<Map<String, String>>() {});
|
final Map<String, String> map = jsonObject.toBean(new TypeReference<Map<String, String>>() {});
|
||||||
|
@ -18,7 +18,6 @@ package org.dromara.hutool.json;
|
|||||||
|
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import org.dromara.hutool.core.collection.ListUtil;
|
import org.dromara.hutool.core.collection.ListUtil;
|
||||||
import org.dromara.hutool.core.convert.ConvertException;
|
|
||||||
import org.dromara.hutool.core.io.file.FileUtil;
|
import org.dromara.hutool.core.io.file.FileUtil;
|
||||||
import org.dromara.hutool.core.map.Dict;
|
import org.dromara.hutool.core.map.Dict;
|
||||||
import org.dromara.hutool.core.reflect.TypeReference;
|
import org.dromara.hutool.core.reflect.TypeReference;
|
||||||
@ -47,7 +46,7 @@ public class JSONArrayTest {
|
|||||||
@Test()
|
@Test()
|
||||||
public void createJSONArrayFromJSONObjectTest() {
|
public void createJSONArrayFromJSONObjectTest() {
|
||||||
// JSONObject实现了Iterable接口,可以转换为JSONArray
|
// JSONObject实现了Iterable接口,可以转换为JSONArray
|
||||||
final JSONObject jsonObject = new JSONObject();
|
final OldJSONObject jsonObject = new OldJSONObject();
|
||||||
|
|
||||||
JSONArray jsonArray = new JSONArray(jsonObject, JSONConfig.of());
|
JSONArray jsonArray = new JSONArray(jsonObject, JSONConfig.of());
|
||||||
assertEquals(new JSONArray(), jsonArray);
|
assertEquals(new JSONArray(), jsonArray);
|
||||||
@ -100,7 +99,7 @@ public class JSONArrayTest {
|
|||||||
public void readJSONArrayFromFileTest() {
|
public void readJSONArrayFromFileTest() {
|
||||||
final JSONArray array = JSONUtil.readJSONArray(FileUtil.file("exam_test.json"), CharsetUtil.UTF_8);
|
final JSONArray array = JSONUtil.readJSONArray(FileUtil.file("exam_test.json"), CharsetUtil.UTF_8);
|
||||||
|
|
||||||
final JSONObject obj0 = array.getJSONObject(0);
|
final OldJSONObject obj0 = array.getJSONObject(0);
|
||||||
final Exam exam = JSONUtil.toBean(obj0, Exam.class);
|
final Exam exam = JSONUtil.toBean(obj0, Exam.class);
|
||||||
assertEquals("0", exam.getAnswerArray()[0].getSeq());
|
assertEquals("0", exam.getAnswerArray()[0].getSeq());
|
||||||
}
|
}
|
||||||
@ -319,7 +318,7 @@ public class JSONArrayTest {
|
|||||||
//noinspection MismatchedQueryAndUpdateOfCollection
|
//noinspection MismatchedQueryAndUpdateOfCollection
|
||||||
final JSONArray array = new JSONArray(jsonArr, null, (mutable) -> {
|
final JSONArray array = new JSONArray(jsonArr, null, (mutable) -> {
|
||||||
if(mutable.getKey() instanceof Integer){
|
if(mutable.getKey() instanceof Integer){
|
||||||
final JSONObject o = (JSONObject) mutable.getValue();
|
final OldJSONObject o = (OldJSONObject) mutable.getValue();
|
||||||
if ("111".equals(o.getStr("id"))) {
|
if ("111".equals(o.getStr("id"))) {
|
||||||
o.set("name", "test1_edit");
|
o.set("name", "test1_edit");
|
||||||
}
|
}
|
||||||
@ -339,7 +338,7 @@ public class JSONArrayTest {
|
|||||||
array.add(JSONUtil.ofObj().set("name", "ccc"));
|
array.add(JSONUtil.ofObj().set("name", "ccc"));
|
||||||
|
|
||||||
StringBuilder result = new StringBuilder();
|
StringBuilder result = new StringBuilder();
|
||||||
array.jsonIter(JSONObject.class).forEach(result::append);
|
array.jsonIter(OldJSONObject.class).forEach(result::append);
|
||||||
assertEquals("{\"name\":\"aaa\"}{\"name\":\"bbb\"}{\"name\":\"ccc\"}", result.toString());
|
assertEquals("{\"name\":\"aaa\"}{\"name\":\"bbb\"}{\"name\":\"ccc\"}", result.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -70,10 +70,10 @@ public class JSONConvertTest {
|
|||||||
tempMap.put("userInfoDict", userInfoDict);
|
tempMap.put("userInfoDict", userInfoDict);
|
||||||
tempMap.put("toSendManIdCard", 1);
|
tempMap.put("toSendManIdCard", 1);
|
||||||
|
|
||||||
final JSONObject obj = JSONUtil.parseObj(tempMap);
|
final OldJSONObject obj = JSONUtil.parseObj(tempMap);
|
||||||
Assertions.assertEquals(new Integer(1), obj.getInt("toSendManIdCard"));
|
Assertions.assertEquals(new Integer(1), obj.getInt("toSendManIdCard"));
|
||||||
|
|
||||||
final JSONObject examInfoDictsJson = obj.getJSONObject("userInfoDict");
|
final OldJSONObject examInfoDictsJson = obj.getJSONObject("userInfoDict");
|
||||||
Assertions.assertEquals(new Integer(1), examInfoDictsJson.getInt("id"));
|
Assertions.assertEquals(new Integer(1), examInfoDictsJson.getInt("id"));
|
||||||
Assertions.assertEquals("质量过关", examInfoDictsJson.getStr("realName"));
|
Assertions.assertEquals("质量过关", examInfoDictsJson.getStr("realName"));
|
||||||
|
|
||||||
@ -90,7 +90,7 @@ public class JSONConvertTest {
|
|||||||
+ " {\n" + " \"id\": 3,\n" + " \"answerIs\": 0,\n" + " \"examType\": 1\n" + " }\n" + " ],\n" //
|
+ " {\n" + " \"id\": 3,\n" + " \"answerIs\": 0,\n" + " \"examType\": 1\n" + " }\n" + " ],\n" //
|
||||||
+ " \"photoPath\": \"yx.mm.com\"\n" + " },\n" + " \"toSendManIdCard\": 1\n" + "}";
|
+ " \"photoPath\": \"yx.mm.com\"\n" + " },\n" + " \"toSendManIdCard\": 1\n" + "}";
|
||||||
|
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(examJson).getJSONObject("examInfoDicts");
|
final OldJSONObject jsonObject = JSONUtil.parseObj(examJson).getJSONObject("examInfoDicts");
|
||||||
final UserInfoDict userInfoDict = jsonObject.toBean(UserInfoDict.class);
|
final UserInfoDict userInfoDict = jsonObject.toBean(UserInfoDict.class);
|
||||||
|
|
||||||
Assertions.assertEquals(userInfoDict.getId(), new Integer(1));
|
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 String jsonStr = "{\"id\":null,\"examInfoDict\":[{\"answerIs\":1, \"id\":null}]}";//JSONUtil.toJsonStr(userInfoDict1);
|
||||||
final JSONObject jsonObject2 = JSONUtil.parseObj(jsonStr);//.getJSONObject("examInfoDicts");
|
final OldJSONObject jsonObject2 = JSONUtil.parseObj(jsonStr);//.getJSONObject("examInfoDicts");
|
||||||
final UserInfoDict userInfoDict2 = jsonObject2.toBean(UserInfoDict.class);
|
final UserInfoDict userInfoDict2 = jsonObject2.toBean(UserInfoDict.class);
|
||||||
Assertions.assertNull(userInfoDict2.getId());
|
Assertions.assertNull(userInfoDict2.getId());
|
||||||
}
|
}
|
||||||
@ -110,7 +110,7 @@ public class JSONConvertTest {
|
|||||||
@Test
|
@Test
|
||||||
public void testJson2Bean2() {
|
public void testJson2Bean2() {
|
||||||
final String jsonStr = ResourceUtil.readUtf8Str("evaluation.json");
|
final String jsonStr = ResourceUtil.readUtf8Str("evaluation.json");
|
||||||
final JSONObject obj = JSONUtil.parseObj(jsonStr);
|
final OldJSONObject obj = JSONUtil.parseObj(jsonStr);
|
||||||
final PerfectEvaluationProductResVo vo = obj.toBean(PerfectEvaluationProductResVo.class);
|
final PerfectEvaluationProductResVo vo = obj.toBean(PerfectEvaluationProductResVo.class);
|
||||||
|
|
||||||
Assertions.assertEquals(obj.getStr("HA001"), vo.getHA001());
|
Assertions.assertEquals(obj.getStr("HA001"), vo.getHA001());
|
||||||
|
@ -42,7 +42,7 @@ public class JSONDeserializerTest {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TestBean deserialize(final JSON json, final Type deserializeType) {
|
public TestBean deserialize(final JSON json, final Type deserializeType) {
|
||||||
final JSONObject valueObj = (JSONObject) json;
|
final OldJSONObject valueObj = (OldJSONObject) json;
|
||||||
this.name = valueObj.getStr("customName");
|
this.name = valueObj.getStr("customName");
|
||||||
this.address = valueObj.getStr("customAddress");
|
this.address = valueObj.getStr("customAddress");
|
||||||
return this;
|
return this;
|
||||||
|
@ -23,7 +23,7 @@ public class JSONNullTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void parseNullTest(){
|
public void parseNullTest(){
|
||||||
final JSONObject bodyjson = JSONUtil.parseObj("{\n" +
|
final OldJSONObject bodyjson = JSONUtil.parseObj("{\n" +
|
||||||
" \"device_model\": null,\n" +
|
" \"device_model\": null,\n" +
|
||||||
" \"device_status_date\": null,\n" +
|
" \"device_status_date\": null,\n" +
|
||||||
" \"imsi\": null,\n" +
|
" \"imsi\": null,\n" +
|
||||||
@ -38,7 +38,7 @@ public class JSONNullTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void parseNullTest2(){
|
public void parseNullTest2(){
|
||||||
final JSONObject bodyjson = JSONUtil.parseObj("{\n" +
|
final OldJSONObject bodyjson = JSONUtil.parseObj("{\n" +
|
||||||
" \"device_model\": null,\n" +
|
" \"device_model\": null,\n" +
|
||||||
" \"device_status_date\": null,\n" +
|
" \"device_status_date\": null,\n" +
|
||||||
" \"imsi\": null,\n" +
|
" \"imsi\": null,\n" +
|
||||||
|
@ -23,7 +23,6 @@ import org.dromara.hutool.core.collection.ListUtil;
|
|||||||
import org.dromara.hutool.core.date.DatePattern;
|
import org.dromara.hutool.core.date.DatePattern;
|
||||||
import org.dromara.hutool.core.date.DateUtil;
|
import org.dromara.hutool.core.date.DateUtil;
|
||||||
import org.dromara.hutool.core.io.resource.ResourceUtil;
|
import org.dromara.hutool.core.io.resource.ResourceUtil;
|
||||||
import org.dromara.hutool.core.lang.Console;
|
|
||||||
import org.dromara.hutool.core.map.MapUtil;
|
import org.dromara.hutool.core.map.MapUtil;
|
||||||
import org.dromara.hutool.core.text.StrUtil;
|
import org.dromara.hutool.core.text.StrUtil;
|
||||||
import org.dromara.hutool.core.util.ObjUtil;
|
import org.dromara.hutool.core.util.ObjUtil;
|
||||||
@ -52,7 +51,7 @@ public class JSONObjectTest {
|
|||||||
public void toStringTest() {
|
public void toStringTest() {
|
||||||
final String str = "{\"code\": 500, \"data\":null}";
|
final String str = "{\"code\": 500, \"data\":null}";
|
||||||
//noinspection MismatchedQueryAndUpdateOfCollection
|
//noinspection MismatchedQueryAndUpdateOfCollection
|
||||||
final JSONObject jsonObject = new JSONObject(str);
|
final OldJSONObject jsonObject = new OldJSONObject(str);
|
||||||
Assertions.assertEquals("{\"code\":500,\"data\":null}", jsonObject.toString());
|
Assertions.assertEquals("{\"code\":500,\"data\":null}", jsonObject.toString());
|
||||||
jsonObject.config().setIgnoreNullValue(true);
|
jsonObject.config().setIgnoreNullValue(true);
|
||||||
Assertions.assertEquals("{\"code\":500}", jsonObject.toString());
|
Assertions.assertEquals("{\"code\":500}", jsonObject.toString());
|
||||||
@ -62,7 +61,7 @@ public class JSONObjectTest {
|
|||||||
public void toStringTest2() {
|
public void toStringTest2() {
|
||||||
final String str = "{\"test\":\"关于开展2018年度“文明集体”、“文明职工”评选表彰活动的通知\"}";
|
final String str = "{\"test\":\"关于开展2018年度“文明集体”、“文明职工”评选表彰活动的通知\"}";
|
||||||
//noinspection MismatchedQueryAndUpdateOfCollection
|
//noinspection MismatchedQueryAndUpdateOfCollection
|
||||||
final JSONObject json = new JSONObject(str);
|
final OldJSONObject json = new OldJSONObject(str);
|
||||||
Assertions.assertEquals(str, json.toString());
|
Assertions.assertEquals(str, json.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -71,7 +70,7 @@ public class JSONObjectTest {
|
|||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
public void toStringTest3() {
|
public void toStringTest3() {
|
||||||
final JSONObject json = Objects.requireNonNull(JSONUtil.ofObj()//
|
final OldJSONObject json = Objects.requireNonNull(JSONUtil.ofObj()//
|
||||||
.set("dateTime", DateUtil.parse("2019-05-02 22:12:01")))//
|
.set("dateTime", DateUtil.parse("2019-05-02 22:12:01")))//
|
||||||
.setDateFormat(DatePattern.NORM_DATE_PATTERN);
|
.setDateFormat(DatePattern.NORM_DATE_PATTERN);
|
||||||
Assertions.assertEquals("{\"dateTime\":\"2019-05-02\"}", json.toString());
|
Assertions.assertEquals("{\"dateTime\":\"2019-05-02\"}", json.toString());
|
||||||
@ -79,7 +78,7 @@ public class JSONObjectTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void toStringWithDateTest() {
|
public void toStringWithDateTest() {
|
||||||
JSONObject json = JSONUtil.ofObj().set("date", DateUtil.parse("2019-05-08 19:18:21"));
|
OldJSONObject json = JSONUtil.ofObj().set("date", DateUtil.parse("2019-05-08 19:18:21"));
|
||||||
assert json != null;
|
assert json != null;
|
||||||
Assertions.assertEquals("{\"date\":1557314301000}", json.toString());
|
Assertions.assertEquals("{\"date\":1557314301000}", json.toString());
|
||||||
|
|
||||||
@ -90,13 +89,13 @@ public class JSONObjectTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void putAllTest() {
|
public void putAllTest() {
|
||||||
final JSONObject json1 = JSONUtil.ofObj()
|
final OldJSONObject json1 = JSONUtil.ofObj()
|
||||||
.set("a", "value1")
|
.set("a", "value1")
|
||||||
.set("b", "value2")
|
.set("b", "value2")
|
||||||
.set("c", "value3")
|
.set("c", "value3")
|
||||||
.set("d", true);
|
.set("d", true);
|
||||||
|
|
||||||
final JSONObject json2 = JSONUtil.ofObj()
|
final OldJSONObject json2 = JSONUtil.ofObj()
|
||||||
.set("a", "value21")
|
.set("a", "value21")
|
||||||
.set("b", "value22");
|
.set("b", "value22");
|
||||||
|
|
||||||
@ -111,7 +110,7 @@ public class JSONObjectTest {
|
|||||||
@Test
|
@Test
|
||||||
public void parseStringTest() {
|
public void parseStringTest() {
|
||||||
final String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}";
|
final String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}";
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(jsonStr);
|
||||||
Assertions.assertEquals(jsonObject.get("a"), "value1");
|
Assertions.assertEquals(jsonObject.get("a"), "value1");
|
||||||
Assertions.assertEquals(jsonObject.get("b"), "value2");
|
Assertions.assertEquals(jsonObject.get("b"), "value2");
|
||||||
Assertions.assertEquals(jsonObject.get("c"), "value3");
|
Assertions.assertEquals(jsonObject.get("c"), "value3");
|
||||||
@ -125,7 +124,7 @@ public class JSONObjectTest {
|
|||||||
public void parseStringTest2() {
|
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\"}";
|
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
|
//noinspection MismatchedQueryAndUpdateOfCollection
|
||||||
final JSONObject json = new JSONObject(jsonStr);
|
final OldJSONObject json = new OldJSONObject(jsonStr);
|
||||||
Assertions.assertEquals("F140", json.getStr("error_code"));
|
Assertions.assertEquals("F140", json.getStr("error_code"));
|
||||||
Assertions.assertEquals("最早发送时间格式错误,该字段可以为空,当不为空时正确填写格式为“YYYYMMDDHHMISS”", json.getStr("error_info"));
|
Assertions.assertEquals("最早发送时间格式错误,该字段可以为空,当不为空时正确填写格式为“YYYYMMDDHHMISS”", json.getStr("error_info"));
|
||||||
}
|
}
|
||||||
@ -134,7 +133,7 @@ public class JSONObjectTest {
|
|||||||
public void parseStringTest3() {
|
public void parseStringTest3() {
|
||||||
final String jsonStr = "{\"test\":\"体”、“文\"}";
|
final String jsonStr = "{\"test\":\"体”、“文\"}";
|
||||||
//noinspection MismatchedQueryAndUpdateOfCollection
|
//noinspection MismatchedQueryAndUpdateOfCollection
|
||||||
final JSONObject json = new JSONObject(jsonStr);
|
final OldJSONObject json = new OldJSONObject(jsonStr);
|
||||||
Assertions.assertEquals("体”、“文", json.getStr("test"));
|
Assertions.assertEquals("体”、“文", json.getStr("test"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -142,7 +141,7 @@ public class JSONObjectTest {
|
|||||||
public void parseStringTest4() {
|
public void parseStringTest4() {
|
||||||
final String jsonStr = "{'msg':'这里还没有内容','data':{'cards':[]},'ok':0}";
|
final String jsonStr = "{'msg':'这里还没有内容','data':{'cards':[]},'ok':0}";
|
||||||
//noinspection MismatchedQueryAndUpdateOfCollection
|
//noinspection MismatchedQueryAndUpdateOfCollection
|
||||||
final JSONObject json = new JSONObject(jsonStr);
|
final OldJSONObject json = new OldJSONObject(jsonStr);
|
||||||
Assertions.assertEquals(new Integer(0), json.getInt("ok"));
|
Assertions.assertEquals(new Integer(0), json.getInt("ok"));
|
||||||
Assertions.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
|
Assertions.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
|
||||||
}
|
}
|
||||||
@ -151,7 +150,7 @@ public class JSONObjectTest {
|
|||||||
public void parseBytesTest() {
|
public void parseBytesTest() {
|
||||||
final String jsonStr = "{'msg':'这里还没有内容','data':{'cards':[]},'ok':0}";
|
final String jsonStr = "{'msg':'这里还没有内容','data':{'cards':[]},'ok':0}";
|
||||||
//noinspection MismatchedQueryAndUpdateOfCollection
|
//noinspection MismatchedQueryAndUpdateOfCollection
|
||||||
final JSONObject json = new JSONObject(jsonStr.getBytes(StandardCharsets.UTF_8));
|
final OldJSONObject json = new OldJSONObject(jsonStr.getBytes(StandardCharsets.UTF_8));
|
||||||
Assertions.assertEquals(new Integer(0), json.getInt("ok"));
|
Assertions.assertEquals(new Integer(0), json.getInt("ok"));
|
||||||
Assertions.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
|
Assertions.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
|
||||||
}
|
}
|
||||||
@ -162,7 +161,7 @@ public class JSONObjectTest {
|
|||||||
final StringReader stringReader = new StringReader(jsonStr);
|
final StringReader stringReader = new StringReader(jsonStr);
|
||||||
|
|
||||||
//noinspection MismatchedQueryAndUpdateOfCollection
|
//noinspection MismatchedQueryAndUpdateOfCollection
|
||||||
final JSONObject json = new JSONObject(stringReader);
|
final OldJSONObject json = new OldJSONObject(stringReader);
|
||||||
Assertions.assertEquals(new Integer(0), json.getInt("ok"));
|
Assertions.assertEquals(new Integer(0), json.getInt("ok"));
|
||||||
Assertions.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
|
Assertions.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
|
||||||
}
|
}
|
||||||
@ -173,7 +172,7 @@ public class JSONObjectTest {
|
|||||||
final ByteArrayInputStream in = new ByteArrayInputStream(jsonStr.getBytes(StandardCharsets.UTF_8));
|
final ByteArrayInputStream in = new ByteArrayInputStream(jsonStr.getBytes(StandardCharsets.UTF_8));
|
||||||
|
|
||||||
//noinspection MismatchedQueryAndUpdateOfCollection
|
//noinspection MismatchedQueryAndUpdateOfCollection
|
||||||
final JSONObject json = new JSONObject(in);
|
final OldJSONObject json = new OldJSONObject(in);
|
||||||
Assertions.assertEquals(new Integer(0), json.getInt("ok"));
|
Assertions.assertEquals(new Integer(0), json.getInt("ok"));
|
||||||
Assertions.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
|
Assertions.assertEquals(new JSONArray(), json.getJSONObject("data").getJSONArray("cards"));
|
||||||
}
|
}
|
||||||
@ -183,15 +182,15 @@ public class JSONObjectTest {
|
|||||||
//在5.3.2之前,</div>中的/会被转义,修复此bug的单元测试
|
//在5.3.2之前,</div>中的/会被转义,修复此bug的单元测试
|
||||||
final String jsonStr = "{\"a\":\"<div>aaa</div>\"}";
|
final String jsonStr = "{\"a\":\"<div>aaa</div>\"}";
|
||||||
//noinspection MismatchedQueryAndUpdateOfCollection
|
//noinspection MismatchedQueryAndUpdateOfCollection
|
||||||
final JSONObject json = new JSONObject(jsonStr);
|
final OldJSONObject json = new OldJSONObject(jsonStr);
|
||||||
Assertions.assertEquals("<div>aaa</div>", json.getObj("a"));
|
Assertions.assertEquals("<div>aaa</div>", json.getObj("a"));
|
||||||
Assertions.assertEquals(jsonStr, json.toString());
|
Assertions.assertEquals(jsonStr, json.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void toBeanTest() {
|
public void toBeanTest() {
|
||||||
final JSONObject subJson = JSONUtil.ofObj().set("value1", "strValue1").set("value2", "234");
|
final OldJSONObject subJson = JSONUtil.ofObj().set("value1", "strValue1").set("value2", "234");
|
||||||
final JSONObject json = JSONUtil.ofObj(JSONConfig.of().setIgnoreError(true)).set("strValue", "strTest").set("intValue", 123)
|
final OldJSONObject json = JSONUtil.ofObj(JSONConfig.of().setIgnoreError(true)).set("strValue", "strTest").set("intValue", 123)
|
||||||
// 测试空字符串转对象
|
// 测试空字符串转对象
|
||||||
.set("doubleValue", "")
|
.set("doubleValue", "")
|
||||||
.set("beanValue", subJson)
|
.set("beanValue", subJson)
|
||||||
@ -210,7 +209,7 @@ public class JSONObjectTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void toBeanNullStrTest() {
|
public void toBeanNullStrTest() {
|
||||||
final JSONObject json = JSONUtil.ofObj(JSONConfig.of().setIgnoreError(true))//
|
final OldJSONObject json = JSONUtil.ofObj(JSONConfig.of().setIgnoreError(true))//
|
||||||
.set("strValue", "null")//
|
.set("strValue", "null")//
|
||||||
.set("intValue", 123)//
|
.set("intValue", 123)//
|
||||||
// 子对象对应"null"字符串,如果忽略错误,跳过,否则抛出转换异常
|
// 子对象对应"null"字符串,如果忽略错误,跳过,否则抛出转换异常
|
||||||
@ -232,7 +231,7 @@ public class JSONObjectTest {
|
|||||||
userA.setDate(new Date());
|
userA.setDate(new Date());
|
||||||
userA.setSqs(ListUtil.of(new Seq("seq1"), new Seq("seq2")));
|
userA.setSqs(ListUtil.of(new Seq("seq1"), new Seq("seq2")));
|
||||||
|
|
||||||
final JSONObject json = JSONUtil.parseObj(userA);
|
final OldJSONObject json = JSONUtil.parseObj(userA);
|
||||||
final UserA userA2 = json.toBean(UserA.class);
|
final UserA userA2 = json.toBean(UserA.class);
|
||||||
// 测试数组
|
// 测试数组
|
||||||
Assertions.assertEquals("seq1", userA2.getSqs().get(0).getSeq());
|
Assertions.assertEquals("seq1", userA2.getSqs().get(0).getSeq());
|
||||||
@ -258,7 +257,7 @@ public class JSONObjectTest {
|
|||||||
@Test
|
@Test
|
||||||
public void toBeanTest5() {
|
public void toBeanTest5() {
|
||||||
final String readUtf8Str = ResourceUtil.readUtf8Str("suiteReport.json");
|
final String readUtf8Str = ResourceUtil.readUtf8Str("suiteReport.json");
|
||||||
final JSONObject json = JSONUtil.parseObj(readUtf8Str);
|
final OldJSONObject json = JSONUtil.parseObj(readUtf8Str);
|
||||||
final SuiteReport bean = json.toBean(SuiteReport.class);
|
final SuiteReport bean = json.toBean(SuiteReport.class);
|
||||||
|
|
||||||
// 第一层
|
// 第一层
|
||||||
@ -277,7 +276,7 @@ public class JSONObjectTest {
|
|||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
public void toBeanTest6() {
|
public void toBeanTest6() {
|
||||||
final JSONObject json = JSONUtil.ofObj()
|
final OldJSONObject json = JSONUtil.ofObj()
|
||||||
.set("targetUrl", "http://test.com")
|
.set("targetUrl", "http://test.com")
|
||||||
.set("success", "true")
|
.set("success", "true")
|
||||||
.set("result", JSONUtil.ofObj()
|
.set("result", JSONUtil.ofObj()
|
||||||
@ -314,7 +313,7 @@ public class JSONObjectTest {
|
|||||||
userA.setDate(new Date());
|
userA.setDate(new Date());
|
||||||
userA.setSqs(ListUtil.of(new Seq(null), new Seq("seq2")));
|
userA.setSqs(ListUtil.of(new Seq(null), new Seq("seq2")));
|
||||||
|
|
||||||
final JSONObject json = JSONUtil.parseObj(userA, false);
|
final OldJSONObject json = JSONUtil.parseObj(userA, false);
|
||||||
|
|
||||||
Assertions.assertTrue(json.containsKey("a"));
|
Assertions.assertTrue(json.containsKey("a"));
|
||||||
Assertions.assertTrue(json.getJSONArray("sqs").getJSONObject(0).containsKey("seq"));
|
Assertions.assertTrue(json.getJSONArray("sqs").getJSONObject(0).containsKey("seq"));
|
||||||
@ -329,7 +328,7 @@ public class JSONObjectTest {
|
|||||||
bean.setStrValue("strTest");
|
bean.setStrValue("strTest");
|
||||||
bean.setTestEnum(TestEnum.TYPE_B);
|
bean.setTestEnum(TestEnum.TYPE_B);
|
||||||
|
|
||||||
final JSONObject json = JSONUtil.parseObj(bean, false);
|
final OldJSONObject json = JSONUtil.parseObj(bean, false);
|
||||||
// 枚举转换检查,更新:枚举原样保存,在writer时调用toString。
|
// 枚举转换检查,更新:枚举原样保存,在writer时调用toString。
|
||||||
Assertions.assertEquals(TestEnum.TYPE_B, json.get("testEnum"));
|
Assertions.assertEquals(TestEnum.TYPE_B, json.get("testEnum"));
|
||||||
|
|
||||||
@ -339,7 +338,7 @@ public class JSONObjectTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void parseBeanTest3() {
|
public void parseBeanTest3() {
|
||||||
final JSONObject json = JSONUtil.ofObj()
|
final OldJSONObject json = JSONUtil.ofObj()
|
||||||
.set("code", 22)
|
.set("code", 22)
|
||||||
.set("data", "{\"jobId\": \"abc\", \"videoUrl\": \"http://a.com/a.mp4\"}");
|
.set("data", "{\"jobId\": \"abc\", \"videoUrl\": \"http://a.com/a.mp4\"}");
|
||||||
|
|
||||||
@ -356,7 +355,7 @@ public class JSONObjectTest {
|
|||||||
userA.setName("nameTest");
|
userA.setName("nameTest");
|
||||||
userA.setDate(new Date());
|
userA.setDate(new Date());
|
||||||
|
|
||||||
final JSONObject userAJson = JSONUtil.parseObj(userA);
|
final OldJSONObject userAJson = JSONUtil.parseObj(userA);
|
||||||
final UserB userB = JSONUtil.toBean(userAJson, UserB.class);
|
final UserB userB = JSONUtil.toBean(userAJson, UserB.class);
|
||||||
|
|
||||||
Assertions.assertEquals(userA.getName(), userB.getName());
|
Assertions.assertEquals(userA.getName(), userB.getName());
|
||||||
@ -370,7 +369,7 @@ public class JSONObjectTest {
|
|||||||
userA.setName("nameTest");
|
userA.setName("nameTest");
|
||||||
userA.setDate(DateUtil.parse("2018-10-25"));
|
userA.setDate(DateUtil.parse("2018-10-25"));
|
||||||
|
|
||||||
final JSONObject userAJson = JSONUtil.parseObj(userA);
|
final OldJSONObject userAJson = JSONUtil.parseObj(userA);
|
||||||
// 自定义日期格式
|
// 自定义日期格式
|
||||||
userAJson.setDateFormat("yyyy-MM-dd");
|
userAJson.setDateFormat("yyyy-MM-dd");
|
||||||
|
|
||||||
@ -380,7 +379,7 @@ public class JSONObjectTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void beanTransTest3() {
|
public void beanTransTest3() {
|
||||||
final JSONObject userAJson = JSONUtil.ofObj()
|
final OldJSONObject userAJson = JSONUtil.ofObj()
|
||||||
.set("a", "AValue")
|
.set("a", "AValue")
|
||||||
.set("name", "nameValue")
|
.set("name", "nameValue")
|
||||||
.set("date", "08:00:00");
|
.set("date", "08:00:00");
|
||||||
@ -395,10 +394,10 @@ public class JSONObjectTest {
|
|||||||
userA.setName("nameTest");
|
userA.setName("nameTest");
|
||||||
userA.setDate(new Date());
|
userA.setDate(new Date());
|
||||||
|
|
||||||
final JSONObject userAJson = JSONUtil.parseObj(userA);
|
final OldJSONObject userAJson = JSONUtil.parseObj(userA);
|
||||||
Assertions.assertFalse(userAJson.containsKey("a"));
|
Assertions.assertFalse(userAJson.containsKey("a"));
|
||||||
|
|
||||||
final JSONObject userAJsonWithNullValue = JSONUtil.parseObj(userA, false);
|
final OldJSONObject userAJsonWithNullValue = JSONUtil.parseObj(userA, false);
|
||||||
Assertions.assertTrue(userAJsonWithNullValue.containsKey("a"));
|
Assertions.assertTrue(userAJsonWithNullValue.containsKey("a"));
|
||||||
Assertions.assertTrue(userAJsonWithNullValue.containsKey("sqs"));
|
Assertions.assertTrue(userAJsonWithNullValue.containsKey("sqs"));
|
||||||
}
|
}
|
||||||
@ -406,7 +405,7 @@ public class JSONObjectTest {
|
|||||||
@Test
|
@Test
|
||||||
public void specialCharTest() {
|
public void specialCharTest() {
|
||||||
final String json = "{\"pattern\": \"[abc]\b\u2001\", \"pattern2Json\": {\"patternText\": \"[ab]\\b\"}}";
|
final String json = "{\"pattern\": \"[abc]\b\u2001\", \"pattern2Json\": {\"patternText\": \"[ab]\\b\"}}";
|
||||||
final JSONObject obj = JSONUtil.parseObj(json);
|
final OldJSONObject obj = JSONUtil.parseObj(json);
|
||||||
Assertions.assertEquals("[abc]\\b\\u2001", obj.getStrEscaped("pattern"));
|
Assertions.assertEquals("[abc]\\b\\u2001", obj.getStrEscaped("pattern"));
|
||||||
Assertions.assertEquals("{\"patternText\":\"[ab]\\b\"}", obj.getStrEscaped("pattern2Json"));
|
Assertions.assertEquals("{\"patternText\":\"[ab]\\b\"}", obj.getStrEscaped("pattern2Json"));
|
||||||
}
|
}
|
||||||
@ -414,7 +413,7 @@ public class JSONObjectTest {
|
|||||||
@Test
|
@Test
|
||||||
public void getStrTest() {
|
public void getStrTest() {
|
||||||
final String json = "{\"name\": \"yyb\\nbbb\"}";
|
final String json = "{\"name\": \"yyb\\nbbb\"}";
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(json);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(json);
|
||||||
|
|
||||||
// 没有转义按照默认规则显示
|
// 没有转义按照默认规则显示
|
||||||
Assertions.assertEquals("yyb\nbbb", jsonObject.getStr("name"));
|
Assertions.assertEquals("yyb\nbbb", jsonObject.getStr("name"));
|
||||||
@ -431,11 +430,11 @@ public class JSONObjectTest {
|
|||||||
beanWithAlias.setValue1("张三");
|
beanWithAlias.setValue1("张三");
|
||||||
beanWithAlias.setValue2(35);
|
beanWithAlias.setValue2(35);
|
||||||
|
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(beanWithAlias);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(beanWithAlias);
|
||||||
Assertions.assertEquals("张三", jsonObject.getStr("name"));
|
Assertions.assertEquals("张三", jsonObject.getStr("name"));
|
||||||
Assertions.assertEquals(new Integer(35), jsonObject.getInt("age"));
|
Assertions.assertEquals(new Integer(35), jsonObject.getInt("age"));
|
||||||
|
|
||||||
final JSONObject json = JSONUtil.ofObj()
|
final OldJSONObject json = JSONUtil.ofObj()
|
||||||
.set("name", "张三")
|
.set("name", "张三")
|
||||||
.set("age", 35);
|
.set("age", 35);
|
||||||
final BeanWithAlias bean = JSONUtil.toBean(Objects.requireNonNull(json).toString(), BeanWithAlias.class);
|
final BeanWithAlias bean = JSONUtil.toBean(Objects.requireNonNull(json).toString(), BeanWithAlias.class);
|
||||||
@ -448,7 +447,7 @@ public class JSONObjectTest {
|
|||||||
final JSONConfig jsonConfig = JSONConfig.of();
|
final JSONConfig jsonConfig = JSONConfig.of();
|
||||||
jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
|
jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||||
|
|
||||||
final JSONObject json = new JSONObject(jsonConfig);
|
final OldJSONObject json = new OldJSONObject(jsonConfig);
|
||||||
json.append("date", DateUtil.parse("2020-06-05 11:16:11"));
|
json.append("date", DateUtil.parse("2020-06-05 11:16:11"));
|
||||||
json.append("bbb", "222");
|
json.append("bbb", "222");
|
||||||
json.append("aaa", "123");
|
json.append("aaa", "123");
|
||||||
@ -461,7 +460,7 @@ public class JSONObjectTest {
|
|||||||
jsonConfig.setDateFormat("yyyy#MM#dd");
|
jsonConfig.setDateFormat("yyyy#MM#dd");
|
||||||
|
|
||||||
final Date date = DateUtil.parse("2020-06-05 11:16:11");
|
final Date date = DateUtil.parse("2020-06-05 11:16:11");
|
||||||
final JSONObject json = new JSONObject(jsonConfig);
|
final OldJSONObject json = new OldJSONObject(jsonConfig);
|
||||||
json.set("date", date);
|
json.set("date", date);
|
||||||
json.set("bbb", "222");
|
json.set("bbb", "222");
|
||||||
json.set("aaa", "123");
|
json.set("aaa", "123");
|
||||||
@ -471,7 +470,7 @@ public class JSONObjectTest {
|
|||||||
Assertions.assertEquals(jsonStr, json.toString());
|
Assertions.assertEquals(jsonStr, json.toString());
|
||||||
|
|
||||||
// 解析测试
|
// 解析测试
|
||||||
final JSONObject parse = JSONUtil.parseObj(jsonStr, jsonConfig);
|
final OldJSONObject parse = JSONUtil.parseObj(jsonStr, jsonConfig);
|
||||||
Assertions.assertEquals(DateUtil.beginOfDay(date), parse.getDate("date"));
|
Assertions.assertEquals(DateUtil.beginOfDay(date), parse.getDate("date"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -481,13 +480,13 @@ public class JSONObjectTest {
|
|||||||
final JSONConfig jsonConfig = JSONConfig.of().setDateFormat("#sss");
|
final JSONConfig jsonConfig = JSONConfig.of().setDateFormat("#sss");
|
||||||
|
|
||||||
final Date date = DateUtil.parse("2020-06-05 11:16:11");
|
final Date date = DateUtil.parse("2020-06-05 11:16:11");
|
||||||
final JSONObject json = new JSONObject(jsonConfig);
|
final OldJSONObject json = new OldJSONObject(jsonConfig);
|
||||||
json.set("date", date);
|
json.set("date", date);
|
||||||
|
|
||||||
Assertions.assertEquals("{\"date\":1591326971}", json.toString());
|
Assertions.assertEquals("{\"date\":1591326971}", json.toString());
|
||||||
|
|
||||||
// 解析测试
|
// 解析测试
|
||||||
final JSONObject parse = JSONUtil.parseObj(json.toString(), jsonConfig);
|
final OldJSONObject parse = JSONUtil.parseObj(json.toString(), jsonConfig);
|
||||||
Assertions.assertEquals(date, DateUtil.date(parse.getDate("date")));
|
Assertions.assertEquals(date, DateUtil.date(parse.getDate("date")));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -497,7 +496,7 @@ public class JSONObjectTest {
|
|||||||
jsonConfig.setDateFormat("#sss");
|
jsonConfig.setDateFormat("#sss");
|
||||||
|
|
||||||
final Date date = DateUtil.parse("2020-06-05 11:16:11");
|
final Date date = DateUtil.parse("2020-06-05 11:16:11");
|
||||||
final JSONObject json = new JSONObject(jsonConfig);
|
final OldJSONObject json = new OldJSONObject(jsonConfig);
|
||||||
json.set("date", date);
|
json.set("date", date);
|
||||||
json.set("bbb", "222");
|
json.set("bbb", "222");
|
||||||
json.set("aaa", "123");
|
json.set("aaa", "123");
|
||||||
@ -507,14 +506,14 @@ public class JSONObjectTest {
|
|||||||
Assertions.assertEquals(jsonStr, json.toString());
|
Assertions.assertEquals(jsonStr, json.toString());
|
||||||
|
|
||||||
// 解析测试
|
// 解析测试
|
||||||
final JSONObject parse = JSONUtil.parseObj(jsonStr, jsonConfig);
|
final OldJSONObject parse = JSONUtil.parseObj(jsonStr, jsonConfig);
|
||||||
Assertions.assertEquals(date, parse.getDate("date"));
|
Assertions.assertEquals(date, parse.getDate("date"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getTimestampTest() {
|
public void getTimestampTest() {
|
||||||
final String timeStr = "1970-01-01 00:00:00";
|
final String timeStr = "1970-01-01 00:00:00";
|
||||||
final JSONObject jsonObject = JSONUtil.ofObj().set("time", timeStr);
|
final OldJSONObject jsonObject = JSONUtil.ofObj().set("time", timeStr);
|
||||||
final Timestamp time = jsonObject.get("time", Timestamp.class);
|
final Timestamp time = jsonObject.get("time", Timestamp.class);
|
||||||
Assertions.assertEquals("1970-01-01 00:00:00.0", time.toString());
|
Assertions.assertEquals("1970-01-01 00:00:00.0", time.toString());
|
||||||
}
|
}
|
||||||
@ -560,7 +559,7 @@ public class JSONObjectTest {
|
|||||||
@Test
|
@Test
|
||||||
public void parseBeanSameNameTest() {
|
public void parseBeanSameNameTest() {
|
||||||
final SameNameBean sameNameBean = new SameNameBean();
|
final SameNameBean sameNameBean = new SameNameBean();
|
||||||
final JSONObject parse = JSONUtil.parseObj(sameNameBean);
|
final OldJSONObject parse = JSONUtil.parseObj(sameNameBean);
|
||||||
Assertions.assertEquals("123", parse.getStr("username"));
|
Assertions.assertEquals("123", parse.getStr("username"));
|
||||||
Assertions.assertEquals("abc", parse.getStr("userName"));
|
Assertions.assertEquals("abc", parse.getStr("userName"));
|
||||||
|
|
||||||
@ -600,7 +599,7 @@ public class JSONObjectTest {
|
|||||||
final Set<Map.Entry<String, String>> entries = of.entrySet();
|
final Set<Map.Entry<String, String>> entries = of.entrySet();
|
||||||
final Map.Entry<String, String> next = entries.iterator().next();
|
final Map.Entry<String, String> next = entries.iterator().next();
|
||||||
|
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(next);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(next);
|
||||||
Assertions.assertEquals("{\"test\":\"testValue\"}", jsonObject.toString());
|
Assertions.assertEquals("{\"test\":\"testValue\"}", jsonObject.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -608,7 +607,7 @@ public class JSONObjectTest {
|
|||||||
public void createJSONObjectTest() {
|
public void createJSONObjectTest() {
|
||||||
Assertions.assertThrows(JSONException.class, ()->{
|
Assertions.assertThrows(JSONException.class, ()->{
|
||||||
// 集合类不支持转为JSONObject
|
// 集合类不支持转为JSONObject
|
||||||
new JSONObject(new JSONArray(), JSONConfig.of());
|
new OldJSONObject(new JSONArray(), JSONConfig.of());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -623,7 +622,7 @@ public class JSONObjectTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void appendTest() {
|
public void appendTest() {
|
||||||
final JSONObject jsonObject = JSONUtil.ofObj().append("key1", "value1");
|
final OldJSONObject jsonObject = JSONUtil.ofObj().append("key1", "value1");
|
||||||
Assertions.assertEquals("{\"key1\":\"value1\"}", jsonObject.toString());
|
Assertions.assertEquals("{\"key1\":\"value1\"}", jsonObject.toString());
|
||||||
|
|
||||||
jsonObject.append("key1", "value2");
|
jsonObject.append("key1", "value2");
|
||||||
@ -635,7 +634,7 @@ public class JSONObjectTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void putByPathTest() {
|
public void putByPathTest() {
|
||||||
final JSONObject json = new JSONObject();
|
final OldJSONObject json = new OldJSONObject();
|
||||||
json.putByPath("aa.bb", "BB");
|
json.putByPath("aa.bb", "BB");
|
||||||
Assertions.assertEquals("{\"aa\":{\"bb\":\"BB\"}}", json.toString());
|
Assertions.assertEquals("{\"aa\":{\"bb\":\"BB\"}}", json.toString());
|
||||||
}
|
}
|
||||||
@ -656,7 +655,7 @@ public class JSONObjectTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void filterIncludeTest() {
|
public void filterIncludeTest() {
|
||||||
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
|
final OldJSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
|
||||||
.set("a", "value1")
|
.set("a", "value1")
|
||||||
.set("b", "value2")
|
.set("b", "value2")
|
||||||
.set("c", "value3")
|
.set("c", "value3")
|
||||||
@ -668,7 +667,7 @@ public class JSONObjectTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void filterExcludeTest() {
|
public void filterExcludeTest() {
|
||||||
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
|
final OldJSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
|
||||||
.set("a", "value1")
|
.set("a", "value1")
|
||||||
.set("b", "value2")
|
.set("b", "value2")
|
||||||
.set("c", "value3")
|
.set("c", "value3")
|
||||||
@ -680,7 +679,7 @@ public class JSONObjectTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void editTest() {
|
public void editTest() {
|
||||||
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
|
final OldJSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
|
||||||
.set("a", "value1")
|
.set("a", "value1")
|
||||||
.set("b", "value2")
|
.set("b", "value2")
|
||||||
.set("c", "value3")
|
.set("c", "value3")
|
||||||
@ -700,7 +699,7 @@ public class JSONObjectTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void toUnderLineCaseTest() {
|
public void toUnderLineCaseTest() {
|
||||||
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
|
final OldJSONObject json1 = JSONUtil.ofObj(JSONConfig.of())
|
||||||
.set("aKey", "value1")
|
.set("aKey", "value1")
|
||||||
.set("bJob", "value2")
|
.set("bJob", "value2")
|
||||||
.set("cGood", "value3")
|
.set("cGood", "value3")
|
||||||
@ -715,7 +714,7 @@ public class JSONObjectTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void nullToEmptyTest() {
|
public void nullToEmptyTest() {
|
||||||
final JSONObject json1 = JSONUtil.ofObj(JSONConfig.of().setIgnoreNullValue(false))
|
final OldJSONObject json1 = JSONUtil.ofObj(JSONConfig.of().setIgnoreNullValue(false))
|
||||||
.set("a", null)
|
.set("a", null)
|
||||||
.set("b", "value2");
|
.set("b", "value2");
|
||||||
|
|
||||||
@ -730,7 +729,7 @@ public class JSONObjectTest {
|
|||||||
public void parseFilterTest() {
|
public void parseFilterTest() {
|
||||||
final String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}";
|
final String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}";
|
||||||
//noinspection MismatchedQueryAndUpdateOfCollection
|
//noinspection MismatchedQueryAndUpdateOfCollection
|
||||||
final JSONObject jsonObject = new JSONObject(jsonStr, null, (pair)-> "b".equals(pair.getKey()));
|
final OldJSONObject jsonObject = new OldJSONObject(jsonStr, null, (pair)-> "b".equals(pair.getKey()));
|
||||||
Assertions.assertEquals(1, jsonObject.size());
|
Assertions.assertEquals(1, jsonObject.size());
|
||||||
Assertions.assertEquals("value2", jsonObject.get("b"));
|
Assertions.assertEquals("value2", jsonObject.get("b"));
|
||||||
}
|
}
|
||||||
@ -739,7 +738,7 @@ public class JSONObjectTest {
|
|||||||
public void parseFilterEditTest() {
|
public void parseFilterEditTest() {
|
||||||
final String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}";
|
final String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\", \"d\": true, \"e\": null}";
|
||||||
//noinspection MismatchedQueryAndUpdateOfCollection
|
//noinspection MismatchedQueryAndUpdateOfCollection
|
||||||
final JSONObject jsonObject = new JSONObject(jsonStr, null, (pair)-> {
|
final OldJSONObject jsonObject = new OldJSONObject(jsonStr, null, (pair)-> {
|
||||||
if("b".equals(pair.getKey())){
|
if("b".equals(pair.getKey())){
|
||||||
final JSONPrimitive primitive = (JSONPrimitive) pair.getValue();
|
final JSONPrimitive primitive = (JSONPrimitive) pair.getValue();
|
||||||
pair.setValue(primitive.getValue() + "_edit");
|
pair.setValue(primitive.getValue() + "_edit");
|
||||||
|
@ -27,7 +27,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|||||||
public class JSONTokenerTest {
|
public class JSONTokenerTest {
|
||||||
@Test
|
@Test
|
||||||
void parseTest() {
|
void parseTest() {
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(ResourceUtil.getUtf8Reader("issue1200.json"));
|
final OldJSONObject jsonObject = JSONUtil.parseObj(ResourceUtil.getUtf8Reader("issue1200.json"));
|
||||||
assertNotNull(jsonObject);
|
assertNotNull(jsonObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -20,8 +20,6 @@ import lombok.Data;
|
|||||||
import org.dromara.hutool.core.collection.ListUtil;
|
import org.dromara.hutool.core.collection.ListUtil;
|
||||||
import org.dromara.hutool.core.date.DateUtil;
|
import org.dromara.hutool.core.date.DateUtil;
|
||||||
import org.dromara.hutool.core.map.MapUtil;
|
import org.dromara.hutool.core.map.MapUtil;
|
||||||
import org.dromara.hutool.core.math.NumberUtil;
|
|
||||||
import org.dromara.hutool.json.serializer.JSONStringer;
|
|
||||||
import org.dromara.hutool.json.test.bean.Price;
|
import org.dromara.hutool.json.test.bean.Price;
|
||||||
import org.dromara.hutool.json.test.bean.UserA;
|
import org.dromara.hutool.json.test.bean.UserA;
|
||||||
import org.dromara.hutool.json.test.bean.UserC;
|
import org.dromara.hutool.json.test.bean.UserC;
|
||||||
@ -126,7 +124,7 @@ public class JSONUtilTest {
|
|||||||
@Test
|
@Test
|
||||||
public void parseNumberToJSONObjectTest() {
|
public void parseNumberToJSONObjectTest() {
|
||||||
assertThrows(JSONException.class, () -> {
|
assertThrows(JSONException.class, () -> {
|
||||||
final JSONObject json = JSONUtil.parseObj(123L);
|
final OldJSONObject json = JSONUtil.parseObj(123L);
|
||||||
Assertions.assertNotNull(json);
|
Assertions.assertNotNull(json);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -136,8 +134,8 @@ public class JSONUtilTest {
|
|||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
public void parseNumberToJSONObjectTest2() {
|
public void parseNumberToJSONObjectTest2() {
|
||||||
final JSONObject json = JSONUtil.parseObj(123L, JSONConfig.of().setIgnoreError(true));
|
final OldJSONObject json = JSONUtil.parseObj(123L, JSONConfig.of().setIgnoreError(true));
|
||||||
assertEquals(new JSONObject(), json);
|
assertEquals(new OldJSONObject(), json);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -171,7 +169,7 @@ public class JSONUtilTest {
|
|||||||
data.put("model", model);
|
data.put("model", model);
|
||||||
data.put("model2", model);
|
data.put("model2", model);
|
||||||
|
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(data);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(data);
|
||||||
|
|
||||||
Assertions.assertTrue(jsonObject.containsKey("model"));
|
Assertions.assertTrue(jsonObject.containsKey("model"));
|
||||||
assertEquals(1, jsonObject.getJSONObject("model").getInt("type").intValue());
|
assertEquals(1, jsonObject.getJSONObject("model").getInt("type").intValue());
|
||||||
@ -182,7 +180,7 @@ public class JSONUtilTest {
|
|||||||
@Test
|
@Test
|
||||||
public void toJsonStrTest3() {
|
public void toJsonStrTest3() {
|
||||||
// 验证某个字段为JSON字符串时转义是否规范
|
// 验证某个字段为JSON字符串时转义是否规范
|
||||||
final JSONObject object = new JSONObject(JSONConfig.of().setIgnoreError(true));
|
final OldJSONObject object = new OldJSONObject(JSONConfig.of().setIgnoreError(true));
|
||||||
object.set("name", "123123");
|
object.set("name", "123123");
|
||||||
object.set("value", "\\");
|
object.set("value", "\\");
|
||||||
object.set("value2", "</");
|
object.set("value2", "</");
|
||||||
@ -190,11 +188,11 @@ public class JSONUtilTest {
|
|||||||
final HashMap<String, String> map = MapUtil.newHashMap();
|
final HashMap<String, String> map = MapUtil.newHashMap();
|
||||||
map.put("user", object.toString());
|
map.put("user", object.toString());
|
||||||
|
|
||||||
final JSONObject json = JSONUtil.parseObj(map);
|
final OldJSONObject json = JSONUtil.parseObj(map);
|
||||||
assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"</\"}", json.get("user"));
|
assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"</\"}", json.get("user"));
|
||||||
assertEquals("{\"user\":\"{\\\"name\\\":\\\"123123\\\",\\\"value\\\":\\\"\\\\\\\\\\\",\\\"value2\\\":\\\"</\\\"}\"}", json.toString());
|
assertEquals("{\"user\":\"{\\\"name\\\":\\\"123123\\\",\\\"value\\\":\\\"\\\\\\\\\\\",\\\"value2\\\":\\\"</\\\"}\"}", json.toString());
|
||||||
|
|
||||||
final JSONObject json2 = JSONUtil.parseObj(json.toString());
|
final OldJSONObject json2 = JSONUtil.parseObj(json.toString());
|
||||||
assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"</\"}", json2.get("user"));
|
assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"</\"}", json2.get("user"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -232,7 +230,7 @@ public class JSONUtilTest {
|
|||||||
final UserC user = JSONUtil.toBean(json, UserC.class);
|
final UserC user = JSONUtil.toBean(json, UserC.class);
|
||||||
Assertions.assertNotNull(user.getProp());
|
Assertions.assertNotNull(user.getProp());
|
||||||
final String prop = user.getProp();
|
final String prop = user.getProp();
|
||||||
final JSONObject propJson = JSONUtil.parseObj(prop);
|
final OldJSONObject propJson = JSONUtil.parseObj(prop);
|
||||||
assertEquals("男", propJson.getStr("gender"));
|
assertEquals("男", propJson.getStr("gender"));
|
||||||
assertEquals(18, propJson.getInt("age").intValue());
|
assertEquals(18, propJson.getInt("age").intValue());
|
||||||
// Assertions.assertEquals("{\"age\":18,\"gender\":\"男\"}", user.getProp());
|
// Assertions.assertEquals("{\"age\":18,\"gender\":\"男\"}", user.getProp());
|
||||||
@ -241,21 +239,21 @@ public class JSONUtilTest {
|
|||||||
@Test
|
@Test
|
||||||
public void getStrTest() {
|
public void getStrTest() {
|
||||||
final String html = "{\"name\":\"Something must have been changed since you leave\"}";
|
final String html = "{\"name\":\"Something must have been changed since you leave\"}";
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(html);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(html);
|
||||||
assertEquals("Something must have been changed since you leave", jsonObject.getStr("name"));
|
assertEquals("Something must have been changed since you leave", jsonObject.getStr("name"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getStrTest2() {
|
public void getStrTest2() {
|
||||||
final String html = "{\"name\":\"Something\\u00a0must have been changed since you leave\"}";
|
final String html = "{\"name\":\"Something\\u00a0must have been changed since you leave\"}";
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(html);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(html);
|
||||||
assertEquals("Something\\u00a0must\\u00a0have\\u00a0been\\u00a0changed\\u00a0since\\u00a0you\\u00a0leave", jsonObject.getStrEscaped("name"));
|
assertEquals("Something\\u00a0must\\u00a0have\\u00a0been\\u00a0changed\\u00a0since\\u00a0you\\u00a0leave", jsonObject.getStrEscaped("name"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void parseFromXmlTest() {
|
public void parseFromXmlTest() {
|
||||||
final String s = "<sfzh>640102197312070614</sfzh><sfz>640102197312070614X</sfz><name>aa</name><gender>1</gender>";
|
final String s = "<sfzh>640102197312070614</sfzh><sfz>640102197312070614X</sfz><name>aa</name><gender>1</gender>";
|
||||||
final JSONObject json = JSONUtil.parseFromXml(s);
|
final OldJSONObject json = JSONUtil.parseFromXml(s);
|
||||||
assertEquals(640102197312070614L, json.get("sfzh"));
|
assertEquals(640102197312070614L, json.get("sfzh"));
|
||||||
assertEquals("640102197312070614X", json.get("sfz"));
|
assertEquals("640102197312070614X", json.get("sfz"));
|
||||||
assertEquals("aa", json.get("name"));
|
assertEquals("aa", json.get("name"));
|
||||||
@ -265,28 +263,20 @@ public class JSONUtilTest {
|
|||||||
@Test
|
@Test
|
||||||
public void doubleTest() {
|
public void doubleTest() {
|
||||||
final String json = "{\"test\": 12.00}";
|
final String json = "{\"test\": 12.00}";
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj(json);
|
final OldJSONObject jsonObject = JSONUtil.parseObj(json);
|
||||||
//noinspection BigDecimalMethodWithoutRoundingCalled
|
//noinspection BigDecimalMethodWithoutRoundingCalled
|
||||||
assertEquals("12.00", jsonObject.getBigDecimal("test").setScale(2).toString());
|
assertEquals("12.00", jsonObject.getBigDecimal("test").setScale(2).toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
public void customValueTest() {
|
|
||||||
final JSONObject jsonObject = JSONUtil.ofObj()
|
|
||||||
.set("test2", (JSONStringer) () -> NumberUtil.format("#.0", 12.00D));
|
|
||||||
|
|
||||||
assertEquals("{\"test2\":12.0}", jsonObject.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void setStripTrailingZerosTest() {
|
public void setStripTrailingZerosTest() {
|
||||||
// 默认去除多余的0
|
// 默认去除多余的0
|
||||||
final JSONObject jsonObjectDefault = JSONUtil.ofObj()
|
final OldJSONObject jsonObjectDefault = JSONUtil.ofObj()
|
||||||
.set("test2", 12.00D);
|
.set("test2", 12.00D);
|
||||||
assertEquals("{\"test2\":12}", jsonObjectDefault.toString());
|
assertEquals("{\"test2\":12}", jsonObjectDefault.toString());
|
||||||
|
|
||||||
// 不去除多余的0
|
// 不去除多余的0
|
||||||
final JSONObject jsonObject = JSONUtil.ofObj(JSONConfig.of().setStripTrailingZeros(false))
|
final OldJSONObject jsonObject = JSONUtil.ofObj(JSONConfig.of().setStripTrailingZeros(false))
|
||||||
.set("test2", 12.00D);
|
.set("test2", 12.00D);
|
||||||
assertEquals("{\"test2\":12.0}", jsonObject.toString());
|
assertEquals("{\"test2\":12.0}", jsonObject.toString());
|
||||||
|
|
||||||
@ -298,7 +288,7 @@ public class JSONUtilTest {
|
|||||||
@Test
|
@Test
|
||||||
public void parseObjTest() {
|
public void parseObjTest() {
|
||||||
// 测试转义
|
// 测试转义
|
||||||
final JSONObject jsonObject = JSONUtil.parseObj("{\n" +
|
final OldJSONObject jsonObject = JSONUtil.parseObj("{\n" +
|
||||||
" \"test\": \"\\\\地库地库\",\n" +
|
" \"test\": \"\\\\地库地库\",\n" +
|
||||||
"}");
|
"}");
|
||||||
|
|
||||||
@ -309,7 +299,7 @@ public class JSONUtilTest {
|
|||||||
public void sqlExceptionTest() {
|
public void sqlExceptionTest() {
|
||||||
//https://github.com/dromara/hutool/issues/1399
|
//https://github.com/dromara/hutool/issues/1399
|
||||||
// SQLException实现了Iterable接口,默认是遍历之,会栈溢出,修正后只返回string
|
// SQLException实现了Iterable接口,默认是遍历之,会栈溢出,修正后只返回string
|
||||||
final JSONObject set = JSONUtil.ofObj().set("test", new SQLException("test"));
|
final OldJSONObject set = JSONUtil.ofObj().set("test", new SQLException("test"));
|
||||||
assertEquals("{\"test\":\"java.sql.SQLException: test\"}", set.toString());
|
assertEquals("{\"test\":\"java.sql.SQLException: test\"}", set.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -322,7 +312,7 @@ public class JSONUtilTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void toXmlTest() {
|
public void toXmlTest() {
|
||||||
final JSONObject obj = JSONUtil.ofObj();
|
final OldJSONObject obj = JSONUtil.ofObj();
|
||||||
obj.set("key1", "v1")
|
obj.set("key1", "v1")
|
||||||
.set("key2", ListUtil.view("a", "b", "c"));
|
.set("key2", ListUtil.view("a", "b", "c"));
|
||||||
final String xmlStr = JSONUtil.toXmlStr(obj);
|
final String xmlStr = JSONUtil.toXmlStr(obj);
|
||||||
|
@ -26,7 +26,7 @@ public class JSONWriterTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void writeDateTest() {
|
public void writeDateTest() {
|
||||||
final JSONObject jsonObject = JSONUtil.ofObj(JSONConfig.of().setDateFormat("yyyy-MM-dd"))
|
final OldJSONObject jsonObject = JSONUtil.ofObj(JSONConfig.of().setDateFormat("yyyy-MM-dd"))
|
||||||
.set("date", DateUtil.parse("2022-09-30"));
|
.set("date", DateUtil.parse("2022-09-30"));
|
||||||
|
|
||||||
// 日期原样写入
|
// 日期原样写入
|
||||||
@ -37,7 +37,7 @@ public class JSONWriterTest {
|
|||||||
Assertions.assertEquals("{\"date\":\"2022-09-30\"}", jsonObject.toString());
|
Assertions.assertEquals("{\"date\":\"2022-09-30\"}", jsonObject.toString());
|
||||||
|
|
||||||
// 自定义日期格式解析生效
|
// 自定义日期格式解析生效
|
||||||
final JSONObject parse = JSONUtil.parseObj(jsonObject.toString(), JSONConfig.of().setDateFormat("yyyy-MM-dd"));
|
final OldJSONObject parse = JSONUtil.parseObj(jsonObject.toString(), JSONConfig.of().setDateFormat("yyyy-MM-dd"));
|
||||||
Assertions.assertEquals(String.class, parse.get("date").getClass());
|
Assertions.assertEquals(String.class, parse.get("date").getClass());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -47,7 +47,7 @@ public class ParseBeanTest {
|
|||||||
final A a = new A();
|
final A a = new A();
|
||||||
a.setBs(ListUtil.of(b1, b2));
|
a.setBs(ListUtil.of(b1, b2));
|
||||||
|
|
||||||
final JSONObject json = JSONUtil.parseObj(a);
|
final OldJSONObject json = JSONUtil.parseObj(a);
|
||||||
final A a1 = JSONUtil.toBean(json, A.class);
|
final A a1 = JSONUtil.toBean(json, A.class);
|
||||||
Assertions.assertEquals(json.toString(), JSONUtil.toJsonStr(a1));
|
Assertions.assertEquals(json.toString(), JSONUtil.toJsonStr(a1));
|
||||||
}
|
}
|
||||||
|
@ -28,7 +28,7 @@ public class Pr3067Test {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getListByPathTest1() {
|
public void getListByPathTest1() {
|
||||||
final JSONObject json = JSONUtil.parseObj(ResourceUtil.readUtf8Str("test_json_path_001.json"));
|
final OldJSONObject json = JSONUtil.parseObj(ResourceUtil.readUtf8Str("test_json_path_001.json"));
|
||||||
final List<TestUser> resultList = json.getByPath("testUserList[1].testArray",
|
final List<TestUser> resultList = json.getByPath("testUserList[1].testArray",
|
||||||
new TypeReference<List<TestUser>>() {});
|
new TypeReference<List<TestUser>>() {});
|
||||||
|
|
||||||
|
@ -22,7 +22,7 @@ import org.junit.jupiter.api.Test;
|
|||||||
public class Pr3507Test {
|
public class Pr3507Test {
|
||||||
@Test
|
@Test
|
||||||
void writeClassTest() {
|
void writeClassTest() {
|
||||||
final JSONObject set = JSONUtil.ofObj().set("name", Pr3507Test.class);
|
final OldJSONObject set = JSONUtil.ofObj().set("name", Pr3507Test.class);
|
||||||
Assertions.assertEquals("{\"name\":\"org.dromara.hutool.json.Pr3507Test\"}", set.toString());
|
Assertions.assertEquals("{\"name\":\"org.dromara.hutool.json.Pr3507Test\"}", set.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -35,7 +35,7 @@ public class TransientTest {
|
|||||||
detailBill.setBizNo("bizNo");
|
detailBill.setBizNo("bizNo");
|
||||||
|
|
||||||
//noinspection MismatchedQueryAndUpdateOfCollection
|
//noinspection MismatchedQueryAndUpdateOfCollection
|
||||||
final JSONObject jsonObject = new JSONObject(detailBill,
|
final OldJSONObject jsonObject = new OldJSONObject(detailBill,
|
||||||
JSONConfig.of().setTransientSupport(false));
|
JSONConfig.of().setTransientSupport(false));
|
||||||
Assertions.assertEquals("{\"id\":\"3243\",\"bizNo\":\"bizNo\"}", jsonObject.toString());
|
Assertions.assertEquals("{\"id\":\"3243\",\"bizNo\":\"bizNo\"}", jsonObject.toString());
|
||||||
}
|
}
|
||||||
@ -47,7 +47,7 @@ public class TransientTest {
|
|||||||
detailBill.setBizNo("bizNo");
|
detailBill.setBizNo("bizNo");
|
||||||
|
|
||||||
//noinspection MismatchedQueryAndUpdateOfCollection
|
//noinspection MismatchedQueryAndUpdateOfCollection
|
||||||
final JSONObject jsonObject = new JSONObject(detailBill,
|
final OldJSONObject jsonObject = new OldJSONObject(detailBill,
|
||||||
JSONConfig.of().setTransientSupport(true));
|
JSONConfig.of().setTransientSupport(true));
|
||||||
Assertions.assertEquals("{\"bizNo\":\"bizNo\"}", jsonObject.toString());
|
Assertions.assertEquals("{\"bizNo\":\"bizNo\"}", jsonObject.toString());
|
||||||
}
|
}
|
||||||
@ -58,7 +58,7 @@ public class TransientTest {
|
|||||||
detailBill.setId("3243");
|
detailBill.setId("3243");
|
||||||
detailBill.setBizNo("bizNo");
|
detailBill.setBizNo("bizNo");
|
||||||
|
|
||||||
final JSONObject jsonObject = new JSONObject(detailBill,
|
final OldJSONObject jsonObject = new OldJSONObject(detailBill,
|
||||||
JSONConfig.of().setTransientSupport(false));
|
JSONConfig.of().setTransientSupport(false));
|
||||||
|
|
||||||
final Bill bill = jsonObject.toBean(Bill.class);
|
final Bill bill = jsonObject.toBean(Bill.class);
|
||||||
@ -72,7 +72,7 @@ public class TransientTest {
|
|||||||
detailBill.setId("3243");
|
detailBill.setId("3243");
|
||||||
detailBill.setBizNo("bizNo");
|
detailBill.setBizNo("bizNo");
|
||||||
|
|
||||||
final JSONObject jsonObject = new JSONObject(detailBill,
|
final OldJSONObject jsonObject = new OldJSONObject(detailBill,
|
||||||
JSONConfig.of().setTransientSupport(true));
|
JSONConfig.of().setTransientSupport(true));
|
||||||
|
|
||||||
final Bill bill = jsonObject.toBean(Bill.class);
|
final Bill bill = jsonObject.toBean(Bill.class);
|
||||||
|
@ -18,7 +18,7 @@ package org.dromara.hutool.json.jwt;
|
|||||||
|
|
||||||
import org.dromara.hutool.core.date.DateUtil;
|
import org.dromara.hutool.core.date.DateUtil;
|
||||||
import org.dromara.hutool.core.date.TimeUtil;
|
import org.dromara.hutool.core.date.TimeUtil;
|
||||||
import org.dromara.hutool.json.JSONObject;
|
import org.dromara.hutool.json.OldJSONObject;
|
||||||
import org.dromara.hutool.json.JSONUtil;
|
import org.dromara.hutool.json.JSONUtil;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import org.junit.jupiter.api.Assertions;
|
import org.junit.jupiter.api.Assertions;
|
||||||
@ -40,7 +40,7 @@ public class IssueI6IS5BTest {
|
|||||||
jwtToken.setIat(iat);
|
jwtToken.setIat(iat);
|
||||||
final String token = JWTUtil.createToken(JSONUtil.parseObj(jwtToken), "123".getBytes(StandardCharsets.UTF_8));
|
final String token = JWTUtil.createToken(JSONUtil.parseObj(jwtToken), "123".getBytes(StandardCharsets.UTF_8));
|
||||||
Assertions.assertEquals("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2Nzc3NzI4MDB9.SXU_mm1wT5lNoK-Dq5Y8f3BItv_44zuAlyeWLqajpXg", token);
|
Assertions.assertEquals("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2Nzc3NzI4MDB9.SXU_mm1wT5lNoK-Dq5Y8f3BItv_44zuAlyeWLqajpXg", token);
|
||||||
final JSONObject payloads = JWTUtil.parseToken(token).getPayloads();
|
final OldJSONObject payloads = JWTUtil.parseToken(token).getPayloads();
|
||||||
Assertions.assertEquals("{\"iat\":1677772800}", payloads.toString());
|
Assertions.assertEquals("{\"iat\":1677772800}", payloads.toString());
|
||||||
final JwtToken o = payloads.toBean(JwtToken.class);
|
final JwtToken o = payloads.toBean(JwtToken.class);
|
||||||
Assertions.assertEquals(iat, o.getIat());
|
Assertions.assertEquals(iat, o.getIat());
|
||||||
@ -58,7 +58,7 @@ public class IssueI6IS5BTest {
|
|||||||
jwtToken.setIat(iat);
|
jwtToken.setIat(iat);
|
||||||
final String token = JWTUtil.createToken(JSONUtil.parseObj(jwtToken), "123".getBytes(StandardCharsets.UTF_8));
|
final String token = JWTUtil.createToken(JSONUtil.parseObj(jwtToken), "123".getBytes(StandardCharsets.UTF_8));
|
||||||
Assertions.assertEquals("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2Nzc3NzI4MDB9.SXU_mm1wT5lNoK-Dq5Y8f3BItv_44zuAlyeWLqajpXg", token);
|
Assertions.assertEquals("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2Nzc3NzI4MDB9.SXU_mm1wT5lNoK-Dq5Y8f3BItv_44zuAlyeWLqajpXg", token);
|
||||||
final JSONObject payloads = JWTUtil.parseToken(token).getPayloads();
|
final OldJSONObject payloads = JWTUtil.parseToken(token).getPayloads();
|
||||||
Assertions.assertEquals("{\"iat\":1677772800}", payloads.toString());
|
Assertions.assertEquals("{\"iat\":1677772800}", payloads.toString());
|
||||||
final JwtToken2 o = payloads.toBean(JwtToken2.class);
|
final JwtToken2 o = payloads.toBean(JwtToken2.class);
|
||||||
Assertions.assertEquals(iat, o.getIat());
|
Assertions.assertEquals(iat, o.getIat());
|
||||||
|
@ -16,7 +16,7 @@
|
|||||||
|
|
||||||
package org.dromara.hutool.json.jwt;
|
package org.dromara.hutool.json.jwt;
|
||||||
|
|
||||||
import org.dromara.hutool.json.JSONObject;
|
import org.dromara.hutool.json.OldJSONObject;
|
||||||
import org.dromara.hutool.json.JSONUtil;
|
import org.dromara.hutool.json.JSONUtil;
|
||||||
import org.junit.jupiter.api.Assertions;
|
import org.junit.jupiter.api.Assertions;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@ -28,7 +28,7 @@ public class IssueI76TRQTest {
|
|||||||
@Test
|
@Test
|
||||||
void createTokenTest() {
|
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 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 JSONObject payload = JSONUtil.parseObj(str);
|
final OldJSONObject payload = JSONUtil.parseObj(str);
|
||||||
final String token = JWTUtil.createToken(payload, "123456".getBytes());
|
final String token = JWTUtil.createToken(payload, "123456".getBytes());
|
||||||
Assertions.assertNotNull(token);
|
Assertions.assertNotNull(token);
|
||||||
|
|
||||||
|
@ -18,7 +18,7 @@ package org.dromara.hutool.json.reader;
|
|||||||
|
|
||||||
import org.dromara.hutool.json.JSON;
|
import org.dromara.hutool.json.JSON;
|
||||||
import org.dromara.hutool.json.JSONConfig;
|
import org.dromara.hutool.json.JSONConfig;
|
||||||
import org.dromara.hutool.json.JSONObject;
|
import org.dromara.hutool.json.OldJSONObject;
|
||||||
import org.junit.jupiter.api.Assertions;
|
import org.junit.jupiter.api.Assertions;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
@ -34,6 +34,6 @@ public class JSONParserTest {
|
|||||||
@Test
|
@Test
|
||||||
void nextToTest() {
|
void nextToTest() {
|
||||||
final String jsonStr = "{\"a\": 1}";
|
final String jsonStr = "{\"a\": 1}";
|
||||||
JSONParser.of(new JSONTokener(jsonStr), JSONConfig.of()).parseTo(new JSONObject());
|
JSONParser.of(new JSONTokener(jsonStr), JSONConfig.of()).parseTo(new OldJSONObject());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -16,11 +16,11 @@
|
|||||||
|
|
||||||
package org.dromara.hutool.json.test.bean;
|
package org.dromara.hutool.json.test.bean;
|
||||||
|
|
||||||
import org.dromara.hutool.json.JSONObject;
|
import org.dromara.hutool.json.OldJSONObject;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public class JSONBean {
|
public class JSONBean {
|
||||||
private int code;
|
private int code;
|
||||||
private JSONObject data;
|
private OldJSONObject data;
|
||||||
}
|
}
|
||||||
|
@ -24,11 +24,11 @@ import org.junit.jupiter.api.Assertions;
|
|||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
public class GlobalValueWritersTest {
|
public class ValueWriterManagerTest {
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
public void init(){
|
public void init(){
|
||||||
GlobalValueWriters.add(new JSONValueWriter() {
|
ValueWriterManager.getInstance().register(new ValueWriter() {
|
||||||
@Override
|
@Override
|
||||||
public void write(final JSONWriter writer, final Object value) {
|
public void write(final JSONWriter writer, final Object value) {
|
||||||
writer.writeRaw(String.valueOf(((CustomSubBean)value).getId()));
|
writer.writeRaw(String.valueOf(((CustomSubBean)value).getId()));
|
@ -16,7 +16,7 @@
|
|||||||
|
|
||||||
package org.dromara.hutool.json.xml;
|
package org.dromara.hutool.json.xml;
|
||||||
|
|
||||||
import org.dromara.hutool.json.JSONObject;
|
import org.dromara.hutool.json.OldJSONObject;
|
||||||
import org.junit.jupiter.api.Assertions;
|
import org.junit.jupiter.api.Assertions;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
@ -24,7 +24,7 @@ public class Issue3560Test {
|
|||||||
@Test
|
@Test
|
||||||
public void toJSONObjectTest() {
|
public void toJSONObjectTest() {
|
||||||
final String inPara= "<ROOT><ID>002317479934367853</ID><CONTENT><![CDATA[asdfadf&21sdgzxv&aasfasf]]></CONTENT></ROOT>";
|
final String inPara= "<ROOT><ID>002317479934367853</ID><CONTENT><![CDATA[asdfadf&21sdgzxv&aasfasf]]></CONTENT></ROOT>";
|
||||||
final JSONObject json = JSONXMLUtil.toJSONObject(inPara, ParseConfig.of().setKeepStrings(true));
|
final OldJSONObject json = JSONXMLUtil.toJSONObject(inPara, ParseConfig.of().setKeepStrings(true));
|
||||||
Assertions.assertEquals("{\"ROOT\":{\"ID\":\"002317479934367853\",\"CONTENT\":\"asdfadf&21sdgzxv&aasfasf\"}}", json.toString());
|
Assertions.assertEquals("{\"ROOT\":{\"ID\":\"002317479934367853\",\"CONTENT\":\"asdfadf&21sdgzxv&aasfasf\"}}", json.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -16,7 +16,7 @@
|
|||||||
|
|
||||||
package org.dromara.hutool.json.xml;
|
package org.dromara.hutool.json.xml;
|
||||||
|
|
||||||
import org.dromara.hutool.json.JSONObject;
|
import org.dromara.hutool.json.OldJSONObject;
|
||||||
import org.dromara.hutool.json.JSONUtil;
|
import org.dromara.hutool.json.JSONUtil;
|
||||||
import org.junit.jupiter.api.Assertions;
|
import org.junit.jupiter.api.Assertions;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@ -25,7 +25,7 @@ public class XMLTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void toXmlTest(){
|
public void toXmlTest(){
|
||||||
final JSONObject put = JSONUtil.ofObj()
|
final OldJSONObject put = JSONUtil.ofObj()
|
||||||
.set("aaa", "你好")
|
.set("aaa", "你好")
|
||||||
.set("键2", "test");
|
.set("键2", "test");
|
||||||
final String s = JSONUtil.toXmlStr(put);
|
final String s = JSONUtil.toXmlStr(put);
|
||||||
@ -35,7 +35,7 @@ public class XMLTest {
|
|||||||
@Test
|
@Test
|
||||||
public void escapeTest(){
|
public void escapeTest(){
|
||||||
final String xml = "<a>•</a>";
|
final String xml = "<a>•</a>";
|
||||||
final JSONObject jsonObject = JSONXMLUtil.toJSONObject(xml);
|
final OldJSONObject jsonObject = JSONXMLUtil.toJSONObject(xml);
|
||||||
|
|
||||||
Assertions.assertEquals("{\"a\":\"•\"}", jsonObject.toString());
|
Assertions.assertEquals("{\"a\":\"•\"}", jsonObject.toString());
|
||||||
|
|
||||||
@ -45,7 +45,7 @@ public class XMLTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void xmlContentTest(){
|
public void xmlContentTest(){
|
||||||
final JSONObject jsonObject = JSONUtil.ofObj().set("content","123456");
|
final OldJSONObject jsonObject = JSONUtil.ofObj().set("content","123456");
|
||||||
|
|
||||||
String xml = JSONXMLUtil.toXml(jsonObject);
|
String xml = JSONXMLUtil.toXml(jsonObject);
|
||||||
Assertions.assertEquals("123456", xml);
|
Assertions.assertEquals("123456", xml);
|
||||||
|
Loading…
x
Reference in New Issue
Block a user