Creating A custom Annotation

Domain

package other.annotation;

@JsonSerializable
public class Car {

    @JsonElement
    private String passengerNum;

    private String weight;

    @JsonElement(key="carName")
    private String name;

    @Init
    private void init(){
        this.name = this.name.substring(0, 1).toUpperCase()
                + this.name.substring(1).toUpperCase();
    }

    public String getPassengerNum() {
        return passengerNum;
    }

    public void setPassengerNum(String passengerNum) {
        this.passengerNum = passengerNum;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Car(String passengerNum, String weight, String name) {
        this.passengerNum = passengerNum;
        this.weight = weight;
        this.name = name;
    }
}

Init Annotation

package other.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Init {
}

JsonElement Annotation

package other.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface JsonElement {
    public String key() default "";
}

JsonSerializable Annotation

package other.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface JsonSerializable {
}

JsonSerializer

package other.annotation;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public class JsonSerializer {
    private void checkIfSerializable(Object object) throws Exception {
        if (Objects.isNull(object)) {
            throw new Exception("The object to serialize is null");
        }

        Class<?> clazz = object.getClass();
        if (!clazz.isAnnotationPresent(JsonSerializable.class)) {
            throw new Exception("The class "
                    + clazz.getSimpleName()
                    + " is not annotated with JsonSerializable");
        }
    }

    private void initializeObject(Object object) throws Exception {
        Class<?> clazz = object.getClass();
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.isAnnotationPresent(Init.class)) {
                method.setAccessible(true);
                method.invoke(object);
            }
        }
    }

    private String getJsonString(Object object) throws Exception {
        Class<?> clazz = object.getClass();
        Map<String, String> jsonElementsMap = new HashMap<>();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            if (field.isAnnotationPresent(JsonElement.class)) {
                jsonElementsMap.put(getKey(field), (String) field.get(object));
            }
        }

        String jsonString = jsonElementsMap.entrySet()
                .stream()
                .map(entry -> "\"" + entry.getKey() + "\":\""
                        + entry.getValue() + "\"")
                .collect(Collectors.joining(","));
        return "{" + jsonString + "}";
    }

    private String getKey(Field field) {
        String key = field.getAnnotation(JsonElement.class).key();
        if(!"".equals(key)){
            return key;
        }
        return field.getName();
    }

    public String convertToJson(Object object) throws Exception {
            checkIfSerializable(object);
            initializeObject(object);
            return getJsonString(object);
    }
}

Tester

package other.annotation;

public class Test {

    public static void main(String[] args) throws Exception {
        Car car = new Car("5", "500", "Jeep");
        JsonSerializer jsonSerializer = new JsonSerializer();
        String result = jsonSerializer.convertToJson(car);
        System.out.println(result);
    }

}

发布了35 篇原创文章 · 获赞 0 · 访问量 2499

猜你喜欢

转载自blog.csdn.net/greywolf5/article/details/104530522