add JSONBeanParser

This commit is contained in:
Looly
2021-08-08 21:36:37 +08:00
parent a9282b9d7c
commit df726654af
8 changed files with 143 additions and 18 deletions

View 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;
}
}

View 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");
}
}
}