mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-07-21 15:09:48 +08:00
add JSONBeanParser
This commit is contained in:
48
hutool-json/src/test/java/cn/hutool/json/IssuesI44E4HTest.java
Executable file
48
hutool-json/src/test/java/cn/hutool/json/IssuesI44E4HTest.java
Executable file
@@ -0,0 +1,48 @@
|
||||
package cn.hutool.json;
|
||||
|
||||
import cn.hutool.json.serialize.GlobalSerializeMapping;
|
||||
import cn.hutool.json.serialize.JSONDeserializer;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* 测试自定义反序列化
|
||||
*/
|
||||
public class IssuesI44E4HTest {
|
||||
|
||||
@Test
|
||||
public void deserializerTest(){
|
||||
GlobalSerializeMapping.put(TestDto.class, (JSONDeserializer<TestDto>) json -> {
|
||||
final TestDto testDto = new TestDto();
|
||||
testDto.setMd(new AcBizModuleMd("name1", ((JSONObject)json).getStr("md")));
|
||||
return testDto;
|
||||
});
|
||||
|
||||
String jsonStr = "{\"md\":\"value1\"}";
|
||||
final TestDto testDto = JSONUtil.toBean(jsonStr, TestDto.class);
|
||||
Assert.assertEquals("value1", testDto.getMd().getValue());
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public static class AcBizModuleMd {
|
||||
private String name;
|
||||
private String value;
|
||||
// 值列表
|
||||
public static final AcBizModuleMd Value1 = new AcBizModuleMd("value1", "name1");
|
||||
public static final AcBizModuleMd Value2 = new AcBizModuleMd("value2", "name2");
|
||||
public static final AcBizModuleMd Value3 = new AcBizModuleMd("value3", "name3");
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class TestDto {
|
||||
private AcBizModuleMd md;
|
||||
}
|
||||
}
|
||||
|
||||
|
30
hutool-json/src/test/java/cn/hutool/json/JSONBeanParserTest.java
Executable file
30
hutool-json/src/test/java/cn/hutool/json/JSONBeanParserTest.java
Executable file
@@ -0,0 +1,30 @@
|
||||
package cn.hutool.json;
|
||||
|
||||
import lombok.Data;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JSONBeanParserTest {
|
||||
|
||||
@Test
|
||||
public void parseTest(){
|
||||
String jsonStr = "{\"customName\": \"customValue\", \"customAddress\": \"customAddressValue\"}";
|
||||
final TestBean testBean = JSONUtil.toBean(jsonStr, TestBean.class);
|
||||
Assert.assertNotNull(testBean);
|
||||
Assert.assertEquals("customValue", testBean.getName());
|
||||
Assert.assertEquals("customAddressValue", testBean.getAddress());
|
||||
}
|
||||
|
||||
@Data
|
||||
static class TestBean implements JSONBeanParser<JSONObject>{
|
||||
|
||||
private String name;
|
||||
private String address;
|
||||
|
||||
@Override
|
||||
public void parse(JSONObject value) {
|
||||
this.name = value.getStr("customName");
|
||||
this.address = value.getStr("customAddress");
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user