JSON注解自定义格式解析

在Spring Boot中,你可以通过自定义注解来格式化或转换属性值。以下是一个示例代码,演示如何实现这个过程:

首先,定义一个注解@CustomFormat,用于标注需要格式化或转换的属性。该注解可以包含一个参数,用于指定格式化或转换的方式。

import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomFormat {
    String value(); // 格式化或转换方式的参数
}

接下来,假设你有一个Java类MyObject,其中包含一个字符串属性myString,你想要对该属性进行自定义的格式化或转换。

public class MyObject {
    @CustomFormat("toUpperCase")
    private String myString;

    // 省略 getter 和 setter 方法
}

在上述示例中,我们在myString属性上使用了@CustomFormat注解,并传入了参数"toUpperCase",表示我们希望将属性值转换为大写。

最后,你可以创建一个自定义的序列化器和反序列化器,在其中处理注解的逻辑。

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.IOException;

public class CustomFormatModule extends SimpleModule {
    public CustomFormatModule() {
        addSerializer(String.class, new CustomFormatSerializer());
        addDeserializer(String.class, new CustomFormatDeserializer());
    }

    private static class CustomFormatSerializer extends JsonSerializer<String> {
        @Override
        public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            // 获取注解的参数值
            CustomFormat annotation = findAnnotation(serializers, CustomFormat.class);
            String format = annotation.value();

            // 根据注解的参数值进行格式化或转换
            if ("toUpperCase".equals(format)) {
                gen.writeString(value.toUpperCase());
            } else if ("toLowerCase".equals(format)) {
                gen.writeString(value.toLowerCase());
            } else {
                gen.writeString(value); // 默认情况直接输出原始值
            }
        }
    }

    private static class CustomFormatDeserializer extends JsonDeserializer<String> {
        @Override
        public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            // 获取注解的参数值
            CustomFormat annotation = findAnnotation(ctxt, CustomFormat.class);
            String format = annotation.value();

            // 根据注解的参数值进行格式化或转换
            String value = p.getValueAsString();
            if ("toUpperCase".equals(format)) {
                return value.toUpperCase();
            } else if ("toLowerCase".equals(format)) {
                return value.toLowerCase();
            } else {
                return value; // 默认情况返回原始值
            }
        }
    }

    private static <T> T findAnnotation(SerializerProvider provider, Class<T> annotationClass) {
        return provider.getConfig().getAnnotationIntrospector().findSerializationAnnotation(provider.getContextualType().getRawClass(), annotationClass);
    }

    private static <T> T findAnnotation(DeserializationContext ctxt, Class<T> annotationClass) {
        return ctxt.getAnnotationIntrospector().findDeserializationAnnotation(ctxt.getContextualType().getRawClass(), annotationClass);
    }
}

在上述代码中,我们创建了一个CustomFormatModule类,继承自SimpleModule,并在其中定义了自定义的序列化器和反序列化器。序列化器负责将属性值按照注解的格式进行格式化或转换,而反序列化器则负责将JSON值转换回对象属性值。

最后,你需要在Spring Boot应用的配置类或配置文件中注册这个自定义模块。

import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JacksonConfig {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customJackson() {
        return builder -> builder.modules(new CustomFormatModule());
    }
}

这样,当你使用ObjectMapper将字符串转换为JSON对象时,就会根据注解的定义进行格式化或转换。

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonString = "{\"myString\":\"hello world\"}";

        ObjectMapper objectMapper = new ObjectMapper();
        MyObject myObject = objectMapper.readValue(jsonString, MyObject.class);

        System.out.println(myObject.getMyString()); // 输出:HELLO WORLD
    }
}

在上述示例中,我们将字符串"hello world"转换为了大写形式。

你可以根据实际需求修改上述示例中的类名、属性名、注解参数以及自定义逻辑,以适应你的情况。

posted @ 2024-01-16 09:45  leo3689  阅读(46)  评论(0编辑  收藏  举报