json的注解
package com.leqienglish.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface JSON {
/**
* json 的key值
* @return
*/
String name();
}
实体与JSON的相互转换工具类
package com.leqienglish.annotation.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.activation.FileDataSource;
import org.json.JSONException;
import org.json.JSONObject;
import com.leqienglish.annotation.JSON;
/**
* json与实体间的相互转换
* 不支持嵌套json 与嵌套实体
* 被转换的实体必须有set,get方法
* @author guona
*
*/
public class EntityAndJSON {
/**
* 将实体转换为json字符串
*
* @param t
* @return
* @throws Exception
*/
public static <T> String toJSON(T t) throws Exception {
JSONObject jsonObject = new JSONObject();
Field[] fieldArr = t.getClass().getDeclaredFields();
for (Field field : fieldArr) {
JSON json = field.getAnnotation(JSON.class);
if (json != null) {
Object value = getValue(t, field);
jsonObject.put(json.name(), value);
}
System.err.println(field.getName());
}
return jsonObject.toString();
}
/**
* 将JSON转换为Object
*
* @param jsonObject
* @param clazT
* @return
* @throws Exception
*/
public static <T> T json2Object(String jsonSt