mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-07-21 15:09:48 +08:00
修复JSON反序列化时,引用字段类型的自定义JsonDeserializer无效
This commit is contained in:
54
hutool-json/src/test/java/Issue2555Test.java
Executable file
54
hutool-json/src/test/java/Issue2555Test.java
Executable file
@@ -0,0 +1,54 @@
|
||||
import cn.hutool.json.JSON;
|
||||
import cn.hutool.json.JSONObject;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import cn.hutool.json.serialize.JSONDeserializer;
|
||||
import cn.hutool.json.serialize.JSONObjectSerializer;
|
||||
import lombok.Data;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class Issue2555Test {
|
||||
|
||||
@Test
|
||||
public void serAndDeserTest(){
|
||||
JSONUtil.putSerializer(MyType.class, new MySerializer());
|
||||
JSONUtil.putDeserializer(MyType.class, new MyDeserializer());
|
||||
|
||||
final SimpleObj simpleObj = new SimpleObj();
|
||||
final MyType child = new MyType();
|
||||
child.setAddress("addrValue1");
|
||||
simpleObj.setMyType(child);
|
||||
|
||||
final String json = JSONUtil.toJsonStr(simpleObj);
|
||||
Assert.assertEquals("{\"myType\":{\"addr\":\"addrValue1\"}}", json);
|
||||
|
||||
//MyDeserializer不会被调用
|
||||
final SimpleObj simpleObj2 = JSONUtil.toBean(json, SimpleObj.class);
|
||||
Assert.assertEquals("addrValue1", simpleObj2.getMyType().getAddress());
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class MyType {
|
||||
private String address;
|
||||
}
|
||||
@Data
|
||||
public static class SimpleObj {
|
||||
private MyType myType;
|
||||
}
|
||||
|
||||
public static class MySerializer implements JSONObjectSerializer<MyType> {
|
||||
@Override
|
||||
public void serialize(JSONObject json, MyType bean) {
|
||||
json.set("addr", bean.getAddress());
|
||||
}
|
||||
}
|
||||
|
||||
public static class MyDeserializer implements JSONDeserializer<MyType>{
|
||||
@Override
|
||||
public MyType deserialize(JSON json) {
|
||||
final MyType myType = new MyType();
|
||||
myType.setAddress(((JSONObject)json).getStr("addr"));
|
||||
return myType;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user