首页 > 其他分享 >JSON注解自定义格式解析

JSON注解自定义格式解析

时间:2024-01-16 09:58:51浏览次数:16  
标签:jackson String 自定义 value JSON import 注解 class

在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"转换为了大写形式。

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

标签:jackson,String,自定义,value,JSON,import,注解,class
From: https://www.cnblogs.com/leo3689/p/17966941

相关文章

  • csharp c# http request get post put delete header respons json 网络请求
    C#中如何模拟一个post请求使用HttpClient代替。以下是修改后的代码示例:usingSystem;usingSystem.Net.Http;usingSystem.Text.Json;classHttpPostExample{privateasyncTask<string>HttpPost(stringUrl,objectpostData){stringpostDataStr=J......
  • python中json.dumps() 与json.dump(),json.load()与json.loads()区别?
    json.dumps()将Python对象转换为JSON字符串,并返回该字符串。而json.dump()将Python对象转换为JSON字符串,并将该字符串写入文件。json.dumps()接受一个Python对象作为参数,而json.dump()接受两个参数:一个Python对象和一个写入数据的文件对象。json.dump()生......
  • SparkStreaming 自定义数据采集器
    本文的前提条件:SparkStreaminginJava参考地址:SparkStreamingCustomReceivers1.自定义数据采集器packagecn.coreqi.receiver;importorg.apache.spark.storage.StorageLevel;importorg.apache.spark.streaming.receiver.Receiver;importjava.util.Random;/**......
  • springboot拦截器@resource注解注入为null解决方案 拦截适配配置
    springboot拦截器@resource注解注入为null解决方案 拦截适配配置为什么@resource注入为nullinteceptor在springcontext之前加载,注入必然是null解决方案加入注解@Bean,注意需要使用@Configuration,而不是@Component解决在Spring添加拦截器之前先自己创建一下这个SpringBean,这样......
  • 前端跨域三种解决方式(CORS、JSONP、代理跨域)
    什么是跨域?跨域是浏览器为了安全而作出的限制策略(所以服务端不涉及到跨域);浏览器请求必须遵循同源策略,即同域名、同端口、同协议;例如:http://www.abc.com到http://www.def.com的请求会出现跨域(域名不同)http://www.abc.com:3000到http://www.abc.com:3001的请求会出现跨域(端口不同......
  • Chrome 插件 V3 版本 Manifest.json 中的内容脚本(Content Scripts)解析
    内容脚本(ContentScripts)指定在用户打开某些网页时要使用的JavaScript或CSS文件。内容脚本是在网页环境中运行的文件。通过使用标准文档对象模型 (DOM),开发者能够读取浏览器所访问网页的详情、更改这些网页,并将信息传递给其父级扩展程序。一、内容脚本功能内容脚本在......
  • docker mysql8使用SSL及使用openssl生成自定义证书
    修改my.cnfvi/docker_data/mysql/conf/my.cnf[client]default-character-set=utf8mb4[mysql]default-character-set=utf8mb4[mysqld]character-set-server=utf8mb4default_authentication_plugin=mysql_native_password#增加sslssl保存,重启mysql容器dockerrestartmysql-8.0.23......
  • 自定义注解实现接口入参字段校验
    使用的类javax.validation导入的包<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId><version>xxxx.RELEASE</version></dependency>通过springb......
  • mvc5接口报错:The JSON request was too large to be deserialized的一种原因
    是mvc5版本的接口,接口使用了dynamic接收数组,json对象数组只有56个,length长度不到10万,但是提交就报TheJSONrequestwastoolargetobedeserialized这个错。在.netcore中,dynamic是不需要前端把字段用stringfy序列化为字符串的就能处理的。但是mvc5如果不在前端把dynamic接收......
  • 自定义监控(kube-prometheus)
       ......