This commit is contained in:
Looly
2024-09-19 17:04:31 +08:00
parent bc3f6cf1ee
commit 59c168a99c
29 changed files with 415 additions and 234 deletions

View File

@@ -85,8 +85,8 @@ public interface JSON extends Converter, Cloneable, Serializable {
* @see BeanPath#getValue(Object)
* @since 4.0.6
*/
default Object getByPath(final String expression) {
return BeanPath.of(expression).getValue(this);
default JSON getByPath(final String expression) {
return (JSON) BeanPath.of(expression).getValue(this);
}
/**

View File

@@ -312,7 +312,7 @@ public class JSONArray extends ListWrapper<JSON> implements JSON, JSONGetter<Int
public void write(final JSONWriter writer) throws JSONException {
writer.beginArray();
CollUtil.forEach(this, (index, value) -> writer.writeField(new MutableEntry<>(index, value)));
writer.end();
writer.endArray();
}
@Override

View File

@@ -50,7 +50,12 @@ public class JSONConfig implements Serializable {
*/
private String dateFormat;
/**
* 是否忽略null值
* 是否忽略null值<br>
* 此选项主要作用于两个阶段:
* <ol>
* <li>Java对象或JSON字符串转为JSON时</li>
* <li>JSON写出或转为JSON字符串时</li>
* </ol>
*/
private boolean ignoreNullValue = true;
/**
@@ -188,7 +193,12 @@ public class JSONConfig implements Serializable {
}
/**
* 设置是否忽略null值
* 设置是否忽略null值<br>
* 此选项主要作用于两个阶段:
* <ol>
* <li>Java对象或JSON字符串转为JSON时</li>
* <li>JSON写出或转为JSON字符串时</li>
* </ol>
*
* @param ignoreNullValue 是否忽略null值
* @return this

View File

@@ -90,7 +90,7 @@ public class JSONObject extends MapWrapper<String, JSON> implements JSON, JSONGe
public void write(final JSONWriter writer) throws JSONException {
writer.beginObj();
this.forEach((key, value) -> writer.writeField(new MutableEntry<>(key, value)));
writer.end();
writer.endObj();
}
// region ----- get

View File

@@ -29,9 +29,9 @@ import java.math.BigInteger;
/**
* JSON原始类型数据封装根据RFC8259规范JSONPrimitive只包含以下类型
* <ul>
* <li>number</li>
* <li>string</li>
* <li>null</li>
* <li>Number</li>
* <li>boolean</li>
* <li>String</li>
* </ul>
*
* @author Looly

View File

@@ -461,8 +461,12 @@ public class JSONUtil {
* @return 对象
* @see JSON#getByPath(String)
*/
public static Object getByPath(final JSON json, final String expression) {
return getByPath(json, expression, null);
public static JSON getByPath(final JSON json, final String expression) {
if ((null == json || StrUtil.isBlank(expression))) {
return null;
}
return json.getByPath(expression);
}
/**

View File

@@ -24,7 +24,6 @@ import org.dromara.hutool.core.convert.impl.TemporalAccessorConverter;
import org.dromara.hutool.core.reflect.ConstructorUtil;
import org.dromara.hutool.core.reflect.TypeReference;
import org.dromara.hutool.core.reflect.TypeUtil;
import org.dromara.hutool.core.reflect.kotlin.KClassUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.json.*;
@@ -182,8 +181,7 @@ public class JSONConverter implements Converter, Serializable {
@SuppressWarnings("unchecked")
private <T> T toBean(final Type targetType, final JSON json) {
// 自定义对象反序列化
final JSONDeserializer<?> deserializer = SerializerManager.getInstance().getDeserializer(targetType);
final JSONDeserializer<?> deserializer = SerializerManager.getInstance().getDeserializer(json, targetType);
if (null != deserializer) {
return (T) deserializer.deserialize(json, targetType);
}
@@ -195,11 +193,6 @@ public class JSONConverter implements Converter, Serializable {
//throw new JSONException("Can not get class from type: {}", targetType);
}
// issue#I5WDP0 对于Kotlin对象由于参数可能非空限制导致无法创建一个默认的对象再赋值
if (KClassUtil.isKotlinClass(rawType) && json instanceof JSONGetter) {
return KClassUtil.newInstance(rawType, new JSONGetterValueProvider<>((JSONGetter<String>) json));
}
final Object value;
// JSON原始类型
if (json instanceof JSONPrimitive) {
@@ -229,7 +222,7 @@ public class JSONConverter implements Converter, Serializable {
}
// 尝试转Bean
if (BeanUtil.isWritableBean(rawType)) {
if (!(json instanceof JSONPrimitive) && BeanUtil.isWritableBean(rawType)) {
return BeanCopier.of(value,
ConstructorUtil.newInstanceIfPossible(rawType), targetType,
InternalJSONUtil.toCopyOptions(config)).copy();

View File

@@ -84,15 +84,7 @@ class JSONArrayMapper {
return;
}
if (source instanceof JSONTokener) {
mapFromTokener((JSONTokener) source, JSONConfig.of(), jsonArray);
}if (source instanceof JSONParser) {
((JSONParser)source).parseTo(jsonArray);
} else if (source instanceof Reader) {
mapFromTokener(new JSONTokener((Reader) source), jsonArray.config(), jsonArray);
} else if (source instanceof InputStream) {
mapFromTokener(new JSONTokener((InputStream) source), jsonArray.config(), jsonArray);
} else if (source instanceof byte[]) {
if (source instanceof byte[]) {
final byte[] bytesSource = (byte[]) source;
if ('[' == bytesSource[0] && ']' == bytesSource[bytesSource.length - 1]) {
mapFromTokener(new JSONTokener(IoUtil.toStream(bytesSource)), jsonArray.config(), jsonArray);

View File

@@ -95,13 +95,7 @@ class JSONObjectMapper {
throw new JSONException("Unsupported type [{}] to JSONObject!", source.getClass());
}
if (source instanceof JSONTokener) {
// JSONTokener
mapFromTokener((JSONTokener) source, jsonObject.config(), jsonObject);
}if (source instanceof JSONParser) {
// JSONParser
((JSONParser) source).parseTo(jsonObject);
} else if (source instanceof Map) {
if (source instanceof Map) {
// Map
for (final Map.Entry<?, ?> e : ((Map<?, ?>) source).entrySet()) {
jsonObject.set(ConvertUtil.toStr(e.getKey()), e.getValue());
@@ -109,10 +103,6 @@ class JSONObjectMapper {
} else if (source instanceof Map.Entry) {
final Map.Entry entry = (Map.Entry) source;
jsonObject.set(ConvertUtil.toStr(entry.getKey()), entry.getValue());
} else if (source instanceof Reader) {
mapFromTokener(new JSONTokener((Reader) source), jsonObject.config(), jsonObject);
} else if (source instanceof InputStream) {
mapFromTokener(new JSONTokener((InputStream) source), jsonObject.config(), jsonObject);
} else if (source instanceof byte[]) {
mapFromTokener(new JSONTokener(IoUtil.toStream((byte[]) source)), jsonObject.config(), jsonObject);
} else if (source instanceof ResourceBundle) {

View File

@@ -32,6 +32,8 @@ import org.dromara.hutool.json.writer.ValueWriterManager;
import org.dromara.hutool.json.xml.JSONXMLParser;
import org.dromara.hutool.json.xml.ParseConfig;
import java.io.InputStream;
import java.io.Reader;
import java.io.Serializable;
import java.util.Optional;
import java.util.function.Predicate;
@@ -94,9 +96,8 @@ public class JSONValueMapper implements Serializable {
JSONXMLParser.of(ParseConfig.of(), this.predicate).parseJSONObject(jsonStr, jsonObject);
return jsonObject;
}
return JSONParser.of(new JSONTokener(source), jsonConfig)
.setPredicate(this.predicate)
.parse();
return mapFromTokener(new JSONTokener(source));
}
/**
@@ -128,12 +129,25 @@ public class JSONValueMapper implements Serializable {
return (JSON) obj;
}
// 读取JSON流
if(obj instanceof JSONTokener){
return mapFromTokener((JSONTokener) obj);
}else if(obj instanceof JSONParser){
return ((JSONParser)obj).parse();
} else if (obj instanceof Reader) {
return mapFromTokener(new JSONTokener((Reader) obj));
} else if (obj instanceof InputStream) {
return mapFromTokener(new JSONTokener((InputStream) obj));
}
// 自定义序列化
final JSONSerializer<Object> serializer = SerializerManager.getInstance().getSerializer(obj);
if (null != serializer) {
return serializer.serialize(obj, new SimpleJSONContext(null, this.jsonConfig));
}
// read
// 原始类型
if (null != ValueWriterManager.getInstance().get(obj)) {
return new JSONPrimitive(obj, jsonConfig);
@@ -161,4 +175,14 @@ public class JSONValueMapper implements Serializable {
throw ExceptionUtil.wrap(exception, JSONException.class);
}
}
/**
* 从{@link JSONTokener} 中读取JSON字符串并转换为JSON
*
* @param tokener {@link JSONTokener}
* @return JSON
*/
private JSON mapFromTokener(final JSONTokener tokener) {
return JSONParser.of(tokener, jsonConfig).setPredicate(this.predicate).parse();
}
}

View File

@@ -15,10 +15,13 @@
*/
/**
* JSONJavaScript Object Notation JavaScript对象表示法封装,包含以下组件:
* JSONJavaScript Object Notation JavaScript对象表示法封装<br>
* 规范见https://www.rfc-editor.org/rfc/rfc8259
* 包含以下组件:
* <ul>
* <li>JSONObject使用键值对表示的数据类型使用"{}"包围</li>
* <li>JSONArray使用列表表示的数据类型使用"[]"包围</li>
* <li>JSONObject 使用键值对表示的数据类型,使用"{}"包围</li>
* <li>JSONArray 使用列表表示的数据类型,使用"[]"包围</li>
* <li>JSONPrimitive表示boolean、String、Number等原始类型</li>
* </ul>
* JSON封装主要包括JSON表示和JSON转换
*

View File

@@ -21,7 +21,7 @@ import org.dromara.hutool.json.JSON;
import java.lang.reflect.Type;
/**
* JSON自定义反序列化接口实现{@link JSON} to Bean使用方式为
* JSON自定义反序列化接口实现{@link JSON} to Bean主要作用于JSON转为Java对象时使用方式为:
* <ul>
* <li>定义好反序列化规则,关联指定类型与转换器实现反序列化。</li>
* <li>使Bean实现此接口调用{@link #deserialize(JSON, Type)}解析字段返回this即可。</li>

View File

@@ -20,7 +20,8 @@ import org.dromara.hutool.json.JSON;
import org.dromara.hutool.json.JSONObject;
/**
* 序列化接口通过实现此接口实现自定义的对象转换为JSON的操作
* 序列化接口通过实现此接口实现自定义的对象转换为JSON的操作<br>
* 序列化主要作用于Java对象转为JSON时
*
* @param <V> 对象类型
* @author Looly

View File

@@ -31,7 +31,8 @@ import java.lang.reflect.Type;
public interface MatcherJSONDeserializer<V> extends JSONDeserializer<V> {
/**
* 匹配反序列化器是否匹配
* 匹配反序列化器是否匹配<br>
* 根据JSON的内容、类型和目标类型精准匹配反序列化器
*
* @param json JSON对象
* @param deserializeType 反序列化类型

View File

@@ -26,7 +26,8 @@ package org.dromara.hutool.json.serializer;
public interface MatcherJSONSerializer<V> extends JSONSerializer<V> {
/**
* 判断是否匹配
* 判断是否匹配<br>
* 根据Java对象内容、类型等信息配合当前JSON所处位置判断是否匹配用于决定是否执行序列化
*
* @param bean 对象
* @param context JSON上下文

View File

@@ -16,11 +16,14 @@
package org.dromara.hutool.json.serializer;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.set.ConcurrentHashSet;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.map.concurrent.SafeConcurrentHashMap;
import org.dromara.hutool.core.reflect.ConstructorUtil;
import org.dromara.hutool.core.reflect.TypeUtil;
import org.dromara.hutool.json.JSON;
import org.dromara.hutool.json.serializer.impl.KotlinDeserializer;
import org.dromara.hutool.json.serializer.impl.TemporalAccessorSerializer;
import org.dromara.hutool.json.serializer.impl.TimeZoneSerializer;
@@ -33,7 +36,19 @@ import java.util.Set;
import java.util.TimeZone;
/**
* JSON序列化和反序列化管理器用于管理JSON序列化器注册和注销自定义序列化器和反序列化器。
* JSON序列化和反序列化管理器用于管理JSON序列化器注册和注销自定义序列化器和反序列化器。<br>
* 此管理器管理着两种类型的序列化器和反序列化器:
* <ul>
* <li>类型精准匹配方式。通过Java对象类型匹配只会匹配查找的类型而不匹配子类。可以调用{@link #register(Type, JSONSerializer)} 和 {@link #register(Type, JSONDeserializer)}注册。</li>
* <li>匹配器Matcher方式。通过判断序列化和反序列化器中match方法找到自定义的序列化和反序列化器可以调用{@link #register(MatcherJSONSerializer)} 和 {@link #register(MatcherJSONDeserializer)}注册。</li>
* </ul>
*
* 管理器的使用分为三种方式:
* <ul>
* <li>全局模式: 使用{@link SerializerManager#getInstance()}调用单例,全局可用。</li>
* <li>实例模式: 使用{@link SerializerManager#of()}创建实例,局部可用。</li>
* <li>自定义模式:使用{@code new SerializerManager()}创建实例,不加载默认的转换器。</li>
* </ul>
*
* @author looly
* @since 6.0.0
@@ -48,7 +63,7 @@ public class SerializerManager {
*/
private static final SerializerManager INSTANCE = new SerializerManager();
static {
registerDefault();
registerDefault(INSTANCE);
}
}
@@ -61,6 +76,17 @@ public class SerializerManager {
return SerializerManager.SingletonHolder.INSTANCE;
}
/**
* 创建SerializerManager附带默认的序列化器和反序列化器
*
* @return SerializerManager
*/
public static SerializerManager of() {
final SerializerManager serializerManager = new SerializerManager();
registerDefault(serializerManager);
return serializerManager;
}
/**
* 用户自定义序列化器,存储自定义匹配规则的一类对象的转换器
*/
@@ -162,10 +188,12 @@ public class SerializerManager {
* @return JSONSerializer
*/
@SuppressWarnings({"unchecked"})
public JSONSerializer<Object> getSerializer(final Object bean) {
for (final MatcherJSONSerializer<?> serializer : this.serializerSet) {
if (serializer.match(bean, null)) {
return (JSONSerializer<Object>) serializer;
public MatcherJSONSerializer<Object> getSerializer(final Object bean) {
if(CollUtil.isNotEmpty(this.serializerSet)){
for (final MatcherJSONSerializer<?> serializer : this.serializerSet) {
if (serializer.match(bean, null)) {
return (MatcherJSONSerializer<Object>) serializer;
}
}
}
return null;
@@ -179,20 +207,21 @@ public class SerializerManager {
*/
@SuppressWarnings("unchecked")
public JSONSerializer<Object> getSerializer(final Type type) {
if(null == type){
if(null == type || CollUtil.isEmpty(this.serializerMap)){
return null;
}
return (JSONSerializer<Object>) getSerializerMap().get(type);
return (JSONSerializer<Object>) this.serializerMap.get(type);
}
/**
* 获取匹配器对应的反序列化器
*
* @param json JSON
* @param type 类型
* @return JSONDeserializer
*/
@SuppressWarnings("unchecked")
public JSONDeserializer<Object> getDeserializer(final Type type) {
public JSONDeserializer<Object> getDeserializer(final JSON json, final Type type) {
final Class<?> rawType = TypeUtil.getClass(type);
if(null == rawType){
return null;
@@ -201,7 +230,23 @@ public class SerializerManager {
return (JSONDeserializer<Object>) ConstructorUtil.newInstanceIfPossible(rawType);
}
return (JSONDeserializer<Object>) getDeserializerMap().get(type);
if(CollUtil.isNotEmpty(this.deserializerMap)){
final JSONDeserializer<?> jsonDeserializer = this.deserializerMap.get(type);
if(null != jsonDeserializer){
return (JSONDeserializer<Object>) jsonDeserializer;
}
}
// Matcher
if(CollUtil.isNotEmpty(this.deserializerSet)){
for (final MatcherJSONDeserializer<?> deserializer : this.deserializerSet) {
if (deserializer.match(json, type)) {
return (JSONDeserializer<Object>) deserializer;
}
}
}
return null;
}
// endregion
@@ -252,9 +297,9 @@ public class SerializerManager {
/**
* 注册默认的序列化器和反序列化器
* @param manager {@code SerializerManager}
*/
private static void registerDefault() {
final SerializerManager manager = SingletonHolder.INSTANCE;
private static void registerDefault(final SerializerManager manager) {
manager.register(LocalDate.class, (JSONSerializer<?>) new TemporalAccessorSerializer(LocalDate.class));
manager.register(LocalDate.class, (JSONDeserializer<?>) new TemporalAccessorSerializer(LocalDate.class));
@@ -266,6 +311,9 @@ public class SerializerManager {
manager.register((MatcherJSONSerializer<TimeZone>) TimeZoneSerializer.INSTANCE);
manager.register((MatcherJSONDeserializer<TimeZone>) TimeZoneSerializer.INSTANCE);
// issue#I5WDP0 对于Kotlin对象由于参数可能非空限制导致无法创建一个默认的对象再赋值
manager.register(KotlinDeserializer.INSTANCE);
}
// endregion
}

View File

@@ -0,0 +1,55 @@
/*
* 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.serializer.impl;
import org.dromara.hutool.core.reflect.TypeUtil;
import org.dromara.hutool.core.reflect.kotlin.KClassUtil;
import org.dromara.hutool.json.JSON;
import org.dromara.hutool.json.JSONGetter;
import org.dromara.hutool.json.convert.JSONGetterValueProvider;
import org.dromara.hutool.json.serializer.MatcherJSONDeserializer;
import java.lang.reflect.Type;
/**
* Kotlin对象反序列化器<br>
* issue#I5WDP0 对于Kotlin对象由于参数可能非空限制导致无法创建一个默认的对象再赋值
*
* @author looly
* @since 6.0.0
*/
public class KotlinDeserializer implements MatcherJSONDeserializer<Object> {
/**
* 单例
*/
public static final MatcherJSONDeserializer<?> INSTANCE = new KotlinDeserializer();
@Override
public boolean match(final JSON json, final Type deserializeType) {
final Class<?> rawType = TypeUtil.getClass(deserializeType);
return json instanceof JSONGetter
&& KClassUtil.isKotlinClass(rawType);
}
@SuppressWarnings("unchecked")
@Override
public Object deserialize(final JSON json, final Type deserializeType) {
final Class<?> rawType = TypeUtil.getClass(deserializeType);
return KClassUtil.newInstance(rawType, new JSONGetterValueProvider<>((JSONGetter<String>) json));
}
}

View File

@@ -77,10 +77,6 @@ public class JSONWriter implements Appendable, Flushable, Closeable {
* 写出当前值是否需要分隔符
*/
private boolean needSeparator;
/**
* 是否为JSONArray模式
*/
private boolean arrayMode;
/**
* 本级别缩进量
*/
@@ -129,12 +125,20 @@ public class JSONWriter implements Appendable, Flushable, Closeable {
@SuppressWarnings("resource")
public JSONWriter beginObj() {
append(CharUtil.DELIM_START);
arrayMode = false;
needSeparator = false;
indent += indentFactor;
return this;
}
/**
* 结束JSON对象默认根据开始的类型补充"}"
*
* @return this
*/
public JSONWriter endObj() {
return end(false);
}
/**
* JSONArray写出开始默认写出"["
*
@@ -143,36 +147,24 @@ public class JSONWriter implements Appendable, Flushable, Closeable {
@SuppressWarnings("resource")
public JSONWriter beginArray() {
append(CharUtil.BRACKET_START);
arrayMode = true;
needSeparator = false;
indent += indentFactor;
return this;
}
/**
* 结束,默认根据开始的类型,补充"}"或"]"
* 结束JSON数组,默认根据开始的类型,补充"]"
*
* @return this
*/
@SuppressWarnings("resource")
public JSONWriter end() {
// 结束子缩进
indent -= indentFactor;
// 换行缩进
writeLF().writeSpace(indent);
append(arrayMode ? CharUtil.BRACKET_END : CharUtil.DELIM_END);
flush();
arrayMode = false;
// 当前对象或数组结束,当新的
needSeparator = true;
return this;
public JSONWriter endArray() {
return end(true);
}
/**
* 写出字段名及字段值,如果字段值是{@code null}且忽略null值则不写出任何内容<br>
* 在{@link #arrayMode} 为 {@code true} 时key是数字此时不写出键只写值
*
* @param pair 键值对
* @param pair 键值对
* @return this
* @since 6.0.0
*/
@@ -189,12 +181,15 @@ public class JSONWriter implements Appendable, Flushable, Closeable {
}
}
if (!arrayMode) {
// JSONObject模式写出键否则只输出值
writeKey(StrUtil.toString(pair.getKey()));
final Object key = pair.getKey();
if (key instanceof Integer) {
// 数组模式,只写出值
return writeValueDirect(pair.getValue(), true);
}
return writeValueDirect(pair.getValue());
// 键值对模式
writeKey(StrUtil.toString(key));
return writeValueDirect(pair.getValue(), false);
}
/**
@@ -326,13 +321,33 @@ public class JSONWriter implements Appendable, Flushable, Closeable {
// ------------------------------------------------------------------------------ Private methods
/**
* 结束,默认根据开始的类型,补充"}"或"]"
*
* @param arrayMode 数组模式true表示数组模式false表示对象模式
* @return this
*/
@SuppressWarnings("resource")
private JSONWriter end(final boolean arrayMode) {
// 结束子缩进
indent -= indentFactor;
// 换行缩进
writeLF().writeSpace(indent);
append(arrayMode ? CharUtil.BRACKET_END : CharUtil.DELIM_END);
flush();
// 当前对象或数组结束,当新的
needSeparator = true;
return this;
}
/**
* 写出值,自动处理分隔符和缩进,自动判断类型,并根据不同类型写出特定格式的值
*
* @param value 值
* @param arrayMode 是否数组模式
* @return this
*/
private JSONWriter writeValueDirect(final Object value) {
private JSONWriter writeValueDirect(final Object value, final boolean arrayMode) {
if (arrayMode) {
if (needSeparator) {
//noinspection resource
@@ -352,7 +367,7 @@ public class JSONWriter implements Appendable, Flushable, Closeable {
/**
* 写出JSON的值根据值类型不同输出不同内容
*
* @param value
* @param value 值
* @return this
*/
@SuppressWarnings("resource")

View File

@@ -100,7 +100,7 @@ public class ValueWriterManager {
private static void registerDefault() {
final ValueWriterManager manager = SingletonHolder.INSTANCE;
// JDK对象最后判断
// manager.register(JdkValueWriter.INSTANCE);
manager.register(JdkValueWriter.INSTANCE);
manager.register(NumberValueWriter.INSTANCE);
manager.register(DateValueWriter.INSTANCE);
manager.register(BooleanValueWriter.INSTANCE);