package com.cyl.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 日期格式
* @author cyl
*
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface JsonFormat {
String pattern() default "yyyy/MM/dd HH:mm:ss";
}
package com.cyl.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 转换json串的属性名称定义
* @author cyl
*
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface JsonProperty {
String value();
}
package com.cyl.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 忽略Json转换
* @author cyl
*
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface JsonIgnore {
}
package com.cyl.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.cyl.annotation.JsonFormat;
import com.cyl.annotation.JsonIgnore;
import com.cyl.annotation.JsonProperty;
/**
* 简单Json转换工具类
*
* @author cyl
*
*/
public class JsonUtil {
/**
* 对象转Json字符串
*
* @param object
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static <T> String toJsonString(Object object) throws IllegalArgumentException, IllegalAccessException {
StringBuffer buffer = new StringBuffer("{");
// 通过反射获取该类对象
Class<? extends Object> clazz = object.getClass();
// 获取clazz类定义的所有属性
Field[] declaredFields = clazz.getDeclaredFields();
int length = declaredFields.length;
int n = 0;
for (Field field : declaredFields) {
n++;
if (field.isAnnotationPresent(JsonIgnore.class)) {// 判断该属性上面是否有JsonIgnore注解
continue;
}
field.setAccessible(true);// 打破访问权限
String name = field.getName();// 获取属性名
Object value = field.get(object);// 获取属性值
if (field.isAnnotationPresent(JsonProperty.class)) {// 判断该属性上面是否有JsonProperty注解
JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class);
name = jsonProperty.value();
}
buffer.append("\"" + name + "\": ");
if (value instanceof String) {
buffer.append("\"" + value + "\"");
} else if (value.getClass().isArray()) {// 判断该属性类型是否为数组
Object[] objects = (Object[]) value;
buffer.append(Arrays.asList(objects));
} else if (value instanceof Date) {
Date date = (Date) value;
if (field.isAnnotationPresent(JsonFormat.class)) {// 判断该属性上面是否有JsonFormat注解
// 转换日期格式
String pattern = field.getAnnotation(JsonFormat.class).pattern();
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
buffer.append(sdf.format(date));
} else {
buffer.append(date.getTime());
}
} else {
buffer.append(value);
}
if (n != length) {
buffer.append(",");
}
}
buffer.append("}");
return buffer.toString();
}
/**
* json字符串转对象
*
* @param jsonStr
* @param clazz
* @return
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws NoSuchFieldException
* @throws ParseException
*/
public static <T> T parseObject(String jsonStr, Class<T> clazz)
throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, NoSuchFieldException, ParseException {
// 获取该类的空参构造器
Constructor<T> constructor = clazz.getDeclaredConstructor();
// 打破构造器访问权限
constructor.setAccessible(true);
// 通过该构造器创建该类实例
T instance = constructor.newInstance();
// 遍历该类定义的属性,封装进fieldMap
Map<String, Field> fieldMap = new HashMap<String, Field>();
for (Field field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(JsonIgnore.class)) {
continue;
} else {
String name = field.getName();
if (field.isAnnotationPresent(JsonProperty.class)) {
name = field.getDeclaredAnnotation(JsonProperty.class).value();
}
fieldMap.put(name, field);
}
}
// System.out.println(fieldMap);
String newStr = jsonStr.replace("{", "").replace("}", "");
// System.out.println(newStr);
String[] strs = newStr.split(",\"");
for (String str : strs) {
// System.out.println(str);
str = str.replace("\"", "");
Field field = fieldMap.get(str.substring(0, str.indexOf(":")).trim());
field.setAccessible(true);
String typeSimpleName = field.getType().getSimpleName();
String trimValue = str.substring(str.indexOf(":") + 1).trim();
//System.out.println(str + "--" + typeSimpleName);
// 给instance实例的各属性进行赋值
if ("String".equals(typeSimpleName)) {
field.set(instance, trimValue);
} else if ("Double".equalsIgnoreCase(typeSimpleName)) {
field.set(instance, Double.parseDouble(trimValue));
} else if ("Long".equalsIgnoreCase(typeSimpleName)) {
field.set(instance, Long.parseLong(trimValue));
} else if ("Integer".equals(typeSimpleName) || "int".equals(typeSimpleName)) {
field.set(instance, Integer.parseInt(trimValue));
} else if ("Float".equalsIgnoreCase(typeSimpleName)) {
field.set(instance, Float.parseFloat(trimValue));
} else if ("Short".equals(typeSimpleName)) {
field.set(instance, Short.parseShort(trimValue));
} else if ("Boolean".equalsIgnoreCase(typeSimpleName)) {
field.set(instance, Boolean.parseBoolean(trimValue));
} else if ("char".equals(typeSimpleName) || "Character".equals(typeSimpleName)) {
field.set(instance, trimValue.toCharArray()[0]);
} else if ("Byte".equals(typeSimpleName)) {
field.set(instance, Byte.parseByte(trimValue));
} else if ("Date".equalsIgnoreCase(typeSimpleName)) {
Date date = null;
if (field.isAnnotationPresent(JsonFormat.class)) {
String pattern = field.getDeclaredAnnotation(JsonFormat.class).pattern();
date = new SimpleDateFormat(pattern).parse(trimValue);
} else {
date = new Date(Long.parseLong(trimValue));
}
field.set(instance, date);
} else if (field.getType().isArray()) {// 判断类型是否是数组
String[] split = trimValue.replace("[", "").replace("]", "").split(",");
judgeArrayType(typeSimpleName, field, instance, split);
} else {
field.set(instance, trimValue);
}
}
return instance;
}
/**
* 判断数组类型
*
* @param typeSimpleName
* @param field
* @param obj
* @param values
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
private static void judgeArrayType(String typeSimpleName, Field field, Object obj, String[] values)
throws IllegalArgumentException, IllegalAccessException {
if ("String[]".equals(typeSimpleName)) {
String[] objs = new String[values.length];
for (int i = 0; i < values.length; i++) {
objs[i] = values[i].trim();
}
field.set(obj, objs);
} else if ("Double[]".equalsIgnoreCase(typeSimpleName)) {
Double[] objs = new Double[values.length];
for (int i = 0; i < values.length; i++) {
objs[i] = Double.parseDouble(values[i].trim());
}
field.set(obj, objs);
} else if ("Long[]".equalsIgnoreCase(typeSimpleName)) {
Long[] objs = new Long[values.length];
for (int i = 0; i < values.length; i++) {
objs[i] = Long.parseLong(values[i].trim());
}
field.set(obj, objs);
} else if ("Integer[]".equals(typeSimpleName) || "int[]".equals(typeSimpleName)) {
Integer[] objs = new Integer[values.length];
for (int i = 0; i < values.length; i++) {
objs[i] = Integer.parseInt(values[i].trim());
}
field.set(obj, objs);
} else if ("Float[]".equalsIgnoreCase(typeSimpleName)) {
Float[] objs = new Float[values.length];
for (int i = 0; i < values.length; i++) {
objs[i] = Float.parseFloat(values[i].trim());
}
field.set(obj, objs);
} else if ("Short[]".equals(typeSimpleName)) {
Short[] objs = new Short[values.length];
for (int i = 0; i < values.length; i++) {
objs[i] = Short.parseShort(values[i].trim());
}
field.set(obj, objs);
} else if ("Boolean[]".equalsIgnoreCase(typeSimpleName)) {
Boolean[] objs = new Boolean[values.length];
for (int i = 0; i < values.length; i++) {
objs[i] = Boolean.parseBoolean(values[i].trim());
}
field.set(obj, objs);
} else if ("char[]".equals(typeSimpleName) || "Character".equals(typeSimpleName)) {
Character[] objs = new Character[values.length];
for (int i = 0; i < values.length; i++) {
objs[i] = values[i].trim().toCharArray()[0];
}
field.set(obj, objs);
} else if ("Byte[]".equals(typeSimpleName)) {
Byte[] objs = new Byte[values.length];
for (int i = 0; i < values.length; i++) {
objs[i] = Byte.parseByte(values[i].trim());
}
field.set(obj, objs);
}
}
}
package com.cyl.test;
import java.util.Date;
import com.cyl.reflect.JsonUtil;
import com.cyl.reflect.Person;
/**
* 测试JsonUtil
* @author cyl
*
*/
public class TsetJsonUtil {
public static void main(String[] args) {
Person person = new Person(111, "lucy", 19, new String[] { "xxx", "yyy", "zzz" }, true, new Date());
person.x = 'd';
person.y = 534;
person.z = 2;
String jsonString = null;
try {
jsonString = JsonUtil.toJsonString(person);
} catch (Exception e) {
e.printStackTrace();
}
// {"id": 111,"user_name": "lucy","age": 19,"hobbies": [xxx, yyy,
// zzz],"xxx_status": true,"createDate": 2021/07/04 19:05:15,"x": d,"y":
// 534,"z": 2}
System.out.println(jsonString);
System.out.println("*******");
try {
Person person2 = JsonUtil.parseObject(jsonString, Person.class);
// Person [id=111, name=lucy, age=19, hobbies=[xxx, yyy, zzz], status=true,
// createDate=Sun Jul 04 19:05:15 CST 2021, x=d, y=534, z=2]
System.out.println(person2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.cyl.reflect;
import java.util.Arrays;
import java.util.Date;
import com.cyl.annotation.JsonFormat;
import com.cyl.annotation.JsonProperty;
public class Person {
private Integer id;
@JsonProperty("user_name")
private String name;
private int age;
//@JsonIgnore
private String[] hobbies;
@JsonProperty("xxx_status")
private Boolean status;
@JsonFormat
private Date createDate;
public char x;
public long y;
public Byte z;
public Person() {
super();
}
public Person(Integer id, String name, int age, String[] hobbies, Boolean status, Date createDate) {
super();
this.id = id;
this.name = name;
this.age = age;
this.hobbies = hobbies;
this.status = status;
this.createDate = createDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + ", hobbies=" + Arrays.toString(hobbies)
+ ", status=" + status + ", createDate=" + createDate + ", x=" + x + ", y=" + y + ", z=" + z + "]";
}
}