Java实体生成json请求参数,其中ignoreList为生成json时忽略的字段名,前提需要引用net.sf.json包,如果是maven项目直接导入
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
</dependency>
下面是工具类代码
public class MockUtil {
private static final JsonConfig jsonConfig = new JsonConfig();
private static final JsonDateValueProcessor processor = new JsonDateValueProcessor();
public static String getMock(Class targetClass, List<String> ignoreList) {
try {
Object o = initBean(targetClass);
jsonConfig.registerJsonValueProcessor(Date.class, processor);
if (ignoreList != null && !ignoreList.isEmpty()) {
jsonConfig.setJsonPropertyFilter((source, name, value) -> {
if (ignoreList.contains(name)) {
return true;
}
return false;
});
}
return JSONObject.fromObject(o, jsonConfig).toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
private static Object initBean(Class sourceBeanClass) throws IllegalAccessException, InstantiationException {
Object target = sourceBeanClass.newInstance();
List<Field> fieldList = new ArrayList<>();
while (sourceBeanClass != null) {//当父类为null的时候说明到达了最上层的父类(Object类).
fieldList.addAll(Arrays.asList(sourceBeanClass.getDeclaredFields()));
sourceBeanClass = sourceBeanClass.getSuperclass(); //得到父类,然后赋给自己
}
for (int i = 0; i < fieldList.size(); i++) {
Field targetField = fieldList.get(i);
targetField.setAccessible(true);
if (targetField.getName().equals("serialVersionUID")) {
continue;
}
String type = targetField.getType().getName();
switch (type) {
case "java.lang.Integer":
case "int":
targetField.set(target, 0);
break;
case "java.lang.Double":
case "double":
targetField.set(target, 0D);
break;
case "java.lang.Float":
case "float":
targetField.set(target, 0F);
break;
case "java.lang.Long":
case "long":
targetField.set(target, 0L);
break;
case "java.lang.Short":
case "short":
targetField.set(target, 0);
break;
case "java.lang.Byte":
case "byte":
targetField.set(target, new Byte("1"));
break;
case "java.lang.Boolean":
case "boolean":
targetField.set(target, true);
break;
case "java.lang.Character":
case "char":
targetField.set(target, (char) 0);
break;
case "java.lang.String":
targetField.set(target, "test");
break;
case "java.util.Date":
targetField.set(target, new Date());
break;
case "java.util.List":
// 如果是List类型,得到其Generic的类型
Type genericType = targetField.getGenericType();
if(genericType == null) continue;
// 如果是泛型参数的类型
if(genericType instanceof ParameterizedType){
ParameterizedType pt = (ParameterizedType) genericType;
//得到泛型里的class类型对象
Class<?> genericClazz = (Class<?>)pt.getActualTypeArguments()[0];
Object t = initBean(genericClazz);
List<Object> data = new ArrayList<>();
data.add(t);
targetField.set(target, data);
}
default:
Object t = initBean(targetField.getType());
targetField.set(target, t);
break;
}
}
return target;
}
public static String getMock(Class targetClass) {
List<String> ignoreList = new ArrayList<>();
ignoreList.add("validity");
ignoreList.add("time");
ignoreList.add("lastEditTime");
return getMock(targetClass, ignoreList);
}
static class JsonDateValueProcessor implements JsonValueProcessor {
private String format = "yyyy-MM-dd";
public JsonDateValueProcessor() {
super();
}
public JsonDateValueProcessor(String format) {
super();
this.format = format;
}
@Override
public Object processArrayValue(Object paramObject, JsonConfig paramJsonConfig) {
return process(paramObject);
}
@Override
public Object processObjectValue(String paramString, Object paramObject, JsonConfig paramJsonConfig) {
return process(paramObject);
}
private Object process(Object value) {
if (value instanceof Date) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
return sdf.format(value);
}
return value == null ? "" : value.toString();
}
}
运行实例:
public class A{
private String name;
private Integer age;
private Double weight;
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public static void main(String[] args) {
System.out.println(MockUtil.getMock(A.class, null));
}
}
运行结果:{"age":0,"birthday":"2017-10-18","name":"test","weight":0},如果需要过滤到部分参数不生成,则在调用getMock方法时传入忽略的字段名,如:
public static void main(String[] args) {
List<String> ignoreList = new ArrayList<>();
ignoreList.add("name");
System.out.println(MockUtil.getMock(A.class, ignoreList));
}
运行结果:{"age":0,"birthday":"2017-10-18","weight":0}
如果需要兼容其他类型,在 switch (type) {}添加对象类型即可,注意基础数据类型和对象类型是有区别的,如int与Integer的type值是不一样的,int的type值为int,而integer的type值为java.lang.Integer