Converter转换规则变更,空对象、空值转为Bean时,创建默认对象,而非nul

This commit is contained in:
Looly
2024-07-11 12:43:27 +08:00
parent dc561b12e3
commit e9e4a49132
6 changed files with 61 additions and 16 deletions

View File

@@ -293,6 +293,12 @@ public class JSONConverter implements Converter, Serializable {
return (T) RecordConverter.INSTANCE.convert(type, value);
}
// 空值转空Bean
if(ObjUtil.isEmpty(value)){
// issue#3649 空值转空对象,则直接实例化
return ConstructorUtil.newInstanceIfPossible(rowType);
}
// 表示非需要特殊转换的对象
return null;
}

View File

@@ -12,8 +12,7 @@
package org.dromara.hutool.json;
import lombok.Getter;
import lombok.Setter;
import lombok.Data;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -23,14 +22,19 @@ public class Issue2564Test {
* 实力类 没有get set方法不能被认为是一个bean
*/
@Test()
public void emptyToBeanTest(){
final String x = "{}";
final A a = JSONUtil.toBean(x, JSONConfig.of().setIgnoreError(true), A.class);
public void emptyToBeanTest() {
// 空对象转为一个空Bean返回默认空实例
String x = "{}" ;
A a = JSONUtil.toBean(x, JSONConfig.of().setIgnoreError(true), A.class);
Assertions.assertEquals(new A(), a);
// 非空对象转为一个空bean转换失败
x = "{\"a\": 1}" ;
a = JSONUtil.toBean(x, JSONConfig.of().setIgnoreError(true), A.class);
Assertions.assertNull(a);
}
@Getter
@Setter
public static class A{
@Data
public static class A {
}
}

View File

@@ -0,0 +1,16 @@
package org.dromara.hutool.json;
import lombok.Data;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class Issue3649Test {
@Test
void toEmptyBeanTest() {
final Object bean = JSONUtil.toBean("{}", JSONConfig.of().setIgnoreError(false), EmptyBean.class);
Assertions.assertEquals(new EmptyBean(), bean);
}
@Data
public static class EmptyBean {}
}