This commit is contained in:
Looly
2024-09-30 00:22:01 +08:00
parent 2114b1c08f
commit a19eb17daa
4 changed files with 82 additions and 5 deletions

View File

@@ -18,6 +18,7 @@ package org.dromara.hutool.json;
import org.dromara.hutool.core.bean.path.BeanPath;
import org.dromara.hutool.core.lang.mutable.MutableEntry;
import org.dromara.hutool.core.reflect.TypeUtil;
import org.dromara.hutool.json.writer.JSONWriter;
import java.io.Serializable;
@@ -260,7 +261,11 @@ public interface JSON extends Serializable {
* @param type {@link Type}
* @return 实体类对象
*/
@SuppressWarnings("unchecked")
default <T> T toBean(final Type type) {
if(JSON.class.isAssignableFrom(TypeUtil.getClass(type))){
return (T) this;
}
return getFactory().toBean(this, type);
}
}

View File

@@ -67,7 +67,7 @@ public class MoshiEngine extends AbstractJSONEngine implements Wrapper<Moshi> {
public void serialize(final Object bean, final OutputStream out) {
final BufferedSink sink = Okio.buffer(Okio.sink(out));
try {
getAdapter(this.moshi, bean.getClass()).toJson(sink, bean);
getAdapter(bean.getClass()).toJson(sink, bean);
} catch (final IOException e) {
throw new JSONException(e);
}
@@ -75,7 +75,7 @@ public class MoshiEngine extends AbstractJSONEngine implements Wrapper<Moshi> {
@Override
public String toJsonString(final Object bean) {
final JsonAdapter<Object> adapter = getAdapter(this.moshi, bean.getClass());
final JsonAdapter<Object> adapter = getAdapter(bean.getClass());
return adapter.toJson(bean);
}
@@ -117,11 +117,10 @@ public class MoshiEngine extends AbstractJSONEngine implements Wrapper<Moshi> {
/**
* 获取并配置{@link JsonAdapter}
*
* @param moshi {@link Moshi}
* @param type Bean类型
* @return this
*/
private JsonAdapter<Object> getAdapter(final Moshi moshi, final Type type) {
private JsonAdapter<Object> getAdapter(final Type type) {
initEngine();
JsonAdapter<Object> adapter = this.moshi.adapter(type);
if (ObjUtil.defaultIfNull(this.config, JSONEngineConfig::isPrettyPrint, false)) {

View File

@@ -39,7 +39,7 @@ public class DefaultDeserializer implements JSONDeserializer<Object> {
public Object deserialize(final JSON json, final Type deserializeType) {
// 当目标类型不确定时返回原JSON
final Class<?> rawType = TypeUtil.getClass(deserializeType);
if (null == rawType || Object.class == rawType || rawType == json.getClass()) {
if (null == rawType || Object.class == rawType || rawType.isAssignableFrom(json.getClass())) {
return json;
}