我们可以使用hutool
中的@Alias
注解去给bean
取别名,例如:
@Data
public static class BeanWithAlias {
@Alias("name")
private String value1;
@Alias("age")
private Integer value2;
}
然后别名不仅能在BeanUtil.copyProperties
中使用,还可以在JSONUtil
中使用:
final BeanWithAlias beanWithAlias = new BeanWithAlias();
beanWithAlias.setValue1("张三");
beanWithAlias.setValue2(35);
final JSONObject jsonObject = JSONUtil.parseObj(beanWithAlias);
Assert.assertEquals("张三", jsonObject.getStr("name"));
Assert.assertEquals(new Integer(35), jsonObject.getInt("age"));
JSONObject json = JSONUtil.createObj()
.set("name", "张三")
.set("age", 35);
final BeanWithAlias bean = JSONUtil.toBean(Objects.requireNonNull(json).toString(), BeanWithAlias.class);
Assert.assertEquals("张三", bean.getValue1());
Assert.assertEquals(new Integer(35), bean.getValue2());
这个注解还是非常方便的