Java工具:自定义注解实体与json相互转换

package com.zycfc.zsf.boot.outreach.util;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor //全参构造
public class Student{

	public static void main(String[] args) throws Exception {
		//根据对象中注解转化不同的json字符串	
	/*	Student stu = Student.builder().name("xiaoming").age("18").build();
		String jsonStr=JSON.toJSONString(returnJsonString(stu));*/
		
	}
	// 根据注解对象转json
	public static Map returnJsonString(Object obj) throws IllegalArgumentException, IllegalAccessException {
		HashMap map = Maps.newHashMap();
		Field[] fields = obj.getClass().getFields();
		for (Field field : fields) {
			ChanFld chanFld = field.getDeclaredAnnotation(ChanFld.class);
			if (chanFld != null) {
				Class type = field.getType();
				// 如果是基础数据类型
				if (type == String.class || type == Boolean.class || type == BigDecimal.class
						|| type == boolean.class) {
					map.put(chanFld.name(), field.get(obj));
					continue;
				}
				// 如果是list
				if (type == List.class) {
					List list = (List) field.get(obj);
					List listMap = Lists.newArrayList();
					for (Object object : list) {
						listMap.add(returnJsonString(object));
					}
					map.put(chanFld.name(), listMap);
					continue;
				}
				// 如果是map
				if (type == Map.class) {
					Map mapKey = Maps.newHashMap();
					Map mapTemp = (Map) field.get(obj);
					Set keySet = mapTemp.keySet();
					for (Object key : keySet) {
						Object object = mapTemp.get(key);
						Map returnJsonString = returnJsonString(object);
						mapKey.put(key, returnJsonString);
					}
					map.put(chanFld.name(), mapKey);
					continue;
				}
				// 如果是对象类型
				map.put(chanFld.name(), returnJsonString(field.get(obj)));
			}
		}
		return map;
	}
	// 根据对应注解json转回对象
	public static Object returnObject(String jsonString, Object obj) throws Exception {
		// Map parseObject = JSON.parseObject(jsonString,Map.class);
		JSONObject parseObject = JSON.parseObject(jsonString);
		Field[] fields = getAllFields(obj.getClass());
		for (Field field : fields) {
			field.setAccessible(true);
			ChanFld chanFld = field.getDeclaredAnnotation(ChanFld.class);
			if (chanFld != null) {
				Object o = parseObject.get(chanFld.name());
				if(o==null) {
					continue;
				}
				Class type = field.getType();
				// 如果是基础数据类型
				if (type == String.class || type == Boolean.class || type == BigDecimal.class
						|| type == boolean.class) {
					field.set(obj, parseObject.get(chanFld.name()));
					continue;
				}
				// 如果是list
				if (type == List.class) {
					JSONArray jsonArray = parseObject.getJSONArray(chanFld.name());
					Type genericType = field.getGenericType();
					if (genericType == null)
						continue;
					// 如果是泛型参数的类型
					if (genericType instanceof ParameterizedType) {
						ParameterizedType pt = (ParameterizedType) genericType;
						// 得到泛型里的class类型对象
						Class accountPrincipalApproveClazz = (Class) pt.getActualTypeArguments()[0];
						Object accountPrincipalApprove = accountPrincipalApproveClazz.newInstance();
						List objList = Lists.newArrayList();
						for (Object object : jsonArray) {
							Object returnObject = returnObject(object.toString(), accountPrincipalApprove);
							objList.add(returnObject);
						}
						field.set(obj, objList);
						continue;
					}
				}
				// 如果是map
				if (type == Map.class) {
					Type genericType = field.getGenericType();
					if (genericType == null)
						continue;
					// 如果是泛型参数的类型
					if (genericType instanceof ParameterizedType) {
						ParameterizedType pt = (ParameterizedType) genericType;
						// 得到泛型里的class类型对象
						Class accountPrincipalApproveClazz = (Class) pt.getActualTypeArguments()[1];
						Object accountPrincipalApprove = accountPrincipalApproveClazz.newInstance();
						Map mapFinal = new HashMap();
						Map map = (Map) parseObject.get(chanFld.name());
						Set keySet = map.keySet();
						for (Object key : keySet) {
							mapFinal.put(key,
									returnObject(map.get(key).toString(), accountPrincipalApprove));
						}
						field.set(obj, mapFinal);
					}
					continue;
				}
				// 如果是对象类型
				Class b = (Class) field.getGenericType();				
				Object returnObject = returnObject(parseObject.get(chanFld.name()).toString(), b.newInstance());
				field.set(obj, returnObject);
			}
		}
		return obj;
	}
	 public static Field[] getAllFields(Class clazz) {
	        List fieldList = Lists.newArrayList();
	        while (clazz != null) {
	            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
	            clazz = clazz.getSuperclass();
	        }
	        Field[] fields = new Field[fieldList.size()];
	        fieldList.toArray(fields);
	        return fields;
	    }
} 
  
package com.zycfc.mpc.process.util;
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;
import com.zycfc.zsf.boot.mpc.client.common.trace.ConvertType;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@Documented
public @interface ChanFld {

    /**
     * 对应的外联接口的实体属性值
     */
    String name();

    /**
     * 对应的接口字段
     */
    String[] xmlName() default {};

    /**
     * 字段中文描述,默认为空值
     */
    String desc() default "";

    /**
     * 格式化的参数
     */
    String pattern() default "";

    /**
     * 翻译类型
     */
    ConvertType convertType() default ConvertType.NONE;

    /**
     * 翻译源字段
     */
    String convertFrom() default "";

    /**
     * 是否为申请交易类型
     */
    boolean applType() default false;

    /**
     * 是否为请求实体
     */
    boolean reqBody() default false;

}

 

你可能感兴趣的:(工具类)