在前后端分离的框架中,当我们开发后台接口保存数据时,需要组装JSON数据来做测试。在准备测试数据时,需要将对象的属性一个个复制出来并赋值,太麻烦!
于是乎,我做了个将实体类自动赋值并解析为json数据。
代码如下:
public class GenJsonTest {
private HashMap getParamValueMap() {
HashMap paramValueMap = new HashMap();
int num = (int)(Math.random()*100+1);
paramValueMap.put(String.class, "test"+num);
paramValueMap.put(Integer.class, num);
paramValueMap.put(int.class, num);
paramValueMap.put(long.class, num);
paramValueMap.put(Long.class, num);
paramValueMap.put(Double.class, 123D);
paramValueMap.put(double.class, 123D);
paramValueMap.put(BigDecimal.class, new BigDecimal(10));
return paramValueMap;
}
public static void main(String[] args) throws Exception {
new GenJsonTest().test(WxUserEntity.class);
}
public <T> T test(Class<T> clazz) throws Exception {
T demo = clazz.newInstance();
Field[] f = clazz.getDeclaredFields();
for (int i = 0; i < f.length; i++) {
//获取属相名
String attributeName = f[i].getName();
String type = f[i].getType().getName();
//将属性名的首字母变为大写,为执行set/get方法做准备
String methodName = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
try {
//获取Test类当前属性的setXXX方法(私有和公有方法)
Method setMethod = clazz.getMethod("set" + methodName, Class.forName(type));
//获取Test类当前属性的setXXX方法(只能获取公有方法)
//执行该set方法
setMethod.invoke(demo, getParamValueMap().get(Class.forName(type)));
} catch (NullPointerException nu) {
// System.out.println(MessageFormat.format("本处{0}类型没有值", type));
System.out.println(String.format("本处%s类型没有值", type));
} catch (NoSuchMethodException e) {
continue;
}
}
System.out.println(JSONObject.toJSONString(demo));
return demo;
}
}
其中WxUserEntity.class为你的实体类,修改这里为你自己的实体类即可。
如果你需要修改参数值,可修改getParamValueMap方法。
版权声明:本文为weixin_43745321原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。