由于项目中用json作为ExtJS传到程序中的数据格式,所以许多地方需要将javaBean转换成为json,或者将list,map转换为json。所以写了一个工具类来做这个工作。实现方式分为两种:
1. 通过一个普通javabean,通过一些过滤字段,来生成json
Java代码
private static JSONObject ObjectToJSON(T t, String[] fields, boolean fieldKind){
Field[] fs = t.getClass().getDeclaredFields();
JSONObject jsonObject = new JSONObject();
for (Field field : fs) {
String propertyName = field.getName();
for (String f : fields) {
try {
if (propertyName.equals(f) == fieldKind) {
String methodName = "get"
+ propertyName.substring(0, 1).toUpperCase()
+ propertyName.substring(1);
Method m = t.getClass().getMethod(methodName);
Object o = m.invoke(t);
jsonObject.put(field.getName(), o instanceof String ? transHTML((String)o) : o);
} else {
continue;
}
} catch (SecurityException e) {
throw new JSONUtilException(e);
} catch (NoSuchMethodException e) {
throw new JSONUtilException(e);
} catch (IllegalArgumentException e) {
throw new JSONUtilException(e);
} catch (JSONException e) {
throw new JSONUtilException(e);
} catch (IllegalAccessException e) {
throw new JSONUtilException(e);
} catch (InvocationTargetException e) {
throw new JSONUtilException(e);
}
}
}
return jsonObject;
}
private static JSONObject ObjectToJSON(T t, String[] fields, boolean fieldKind){
Field[] fs = t.getClass().getDeclaredFields();
JSONObject jsonObject = new JSONObject();
for (Field field : fs) {
String propertyName = field.getName();
for (String f : fields) {
try {
if (propertyName.equals(f) == fieldKind) {
String methodName = "get"
+ propertyName.substring(0, 1).toUpperCase()
+ propertyName.substring(1);
Method m = t.getClass().getMethod(methodName);
Object o = m.invoke(t);
jsonObject.put(field.getName(), o instanceof String ? transHTML((String)o) : o);
} else {
continue;
}
} catch (SecurityException e) {
throw new JSONUtilException(e);
} catch (NoSuchMethodException e) {
throw new JSONUtilException(e);
} catch (IllegalArgumentException e) {
throw new JSONUtilException(e);
} catch (JSONException e) {
throw new JSONUtilException(e);
} catch (IllegalAccessException e) {
throw new JSONUtilException(e);
} catch (InvocationTargetException e) {
throw new JSONUtilException(e);
}
}
}
return jsonObject;
}
第一个参数是需要转换的bean,第二个参数为过滤字段,第三个参数是是否需要过滤的字段。也就是说,fieldKind为true时说明生成的json只包含第二个参数中的这些字段。如果fieldKind为false,生成json不包含这些字段
2. 通过在javabean类的属性上用annotation来表示是否需要生成到json中,并且通过可以通过在字段上设置children annotation来定义嵌套
Java代码
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Json {
String jsonName() default ""