[url]http://www.iteye.com/topic/484519[/url]已发布了成型工具包,还包括相关工具.
定义一个注解
实体
转换函数
运用
定义一个注解
@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.FIELD })
public @interface JSONValue {
}
实体
package com.ask.admin.entity;
public class Favorite implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8350231152253261408L;
// 编号
@JSONValue
private int id;
// 标题
@JSONValue
private String title;
// 地址
@JSONValue
private String uri;
// 分类
private int fCategory;
// 描述
@JSONValue
private String fdesc;
// 状态
private int status;
private int author;
private FavoriteCategory favoriteCategory = new FavoriteCategory();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public int getFCategory() {
return fCategory;
}
public void setFCategory(int category) {
fCategory = category;
}
public String getFdesc() {
return fdesc;
}
public void setFdesc(String fdesc) {
this.fdesc = fdesc;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getAuthor() {
return author;
}
public void setAuthor(int author) {
this.author = author;
}
public FavoriteCategory getFavoriteCategory() {
return favoriteCategory;
}
public void setFavoriteCategory(FavoriteCategory favoriteCategory) {
this.favoriteCategory = favoriteCategory;
}
}
转换函数
public class EntityConversionJSON {
@AskLogger
private static Logger logger;
/**
* 实体的值转成JSON对象的值
*
* @param source
* @param dest
*/
public static void entityToJSON(Object source, JSONObject dest) {
Class clzss = source.getClass();
Field[] fields = clzss.getDeclaredFields();
try {
for (Field field : fields) {
//确认是否带有JSONValue注解
if (field.getAnnotation(JSONValue.class) != null) {
dest.put(field.getName(), getFieldValue(source, field
.getName()));
}
}
} catch (Exception e) {
logger.error(e);
throw new RuntimeException(e);
}
}
/**
* 获取字段的值
*
* @param data
* @param fieldName
* @return
*/
public static Object getFieldValue(Object data, String fieldName) {
StringBuilder sb = new StringBuilder();
Class clzss = data.getClass();
//将字段首字母大写
String firstWord = fieldName.substring(0, 1).toUpperCase();
sb.append(firstWord);
sb.append(fieldName.substring(1, fieldName.length()));
final String methodName = "get" + sb.toString();
Method[] methods = clzss.getDeclaredMethods();
try {
for (Method method : methods) {
// 调用对应的方法
if (methodName.equals(method.getName())) {
return method.invoke(data, new Object[] {});
}
}
} catch (Exception e) {
logger.error(e);
throw new RuntimeException(e);
}
return null;
}
}
运用
JSONObject jsonFavorite = new JSONObject();
EntityConversionJSON.entityToJSON(favorite, jsonFavorite);