zoukankan      html  css  js  c++  java
  • Jackson总结:常用注解、整合spring、自定义JsonSerializer

    原文地址:https://www.jianshu.com/p/63c5985fb48e

    Jackson作为springMVC默认的MessageConverter(消息序列化工具),经常在项目中使用,如果熟悉Jackson常用的使用方法,特性化机制,就会事半功倍,极大提高前后端数据交互的灵活性。

    maven依赖

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.5</version>
    </dependency>

    使用jackson需要三个jar包,jackson-databind、jackson-core和jackson-annotations,添加一个依赖jackson-databind就可以拥有这三个jar包。

    jackson基础功能

    jackson使用的最多的就是jackson-databind包,官方文档地址是https://github.com/FasterXML/jackson-databind,使用jackson序列化对象使用ObjectMapper类,如下:

    ObjectMapper objectMapper = new ObjectMapper();
    User user = new User("zhangsan", "123456");
    // class to json
    String userStr = objectMapper.writeValueAsString(user);
    // json to class
    User user2 = objectMapper.readValue(userStr, User.class);

    jackson常用注解使用

    jackson注解主要涉及到的jar包为jackson-annotations.jar,官方文档地址https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations

    1. @JsonProperty 用在属性或者方法上面,用于改变序列化时字段的名称

    public class User {
    @JsonProperty("user_name")
    public String username;
    public String password;
    }
    
    // 序列化为如下格式username变成了user_name
    {"password":"123456","user_name":"zhangsan"}
    

    2. @JsonIgnoreProperties 用在类上面,用于在序列化时忽略指定字段

    ####@JsonIgnoreProperties({"username", "price"})
    
    public class Pet {
    
    private String username;
    private String password;
    private Date birthday;
    private Double price;
    }
    
    // 指定序列化时忽略username、price字段
    {"password":"123456","birthday":1533887811261}

    3. @JsonIgnore 用在属性上面,用于序列化时忽略该属性

    public class Pet {
    
    @JsonIgnore
    private String username;
    private String password;
    private Date birthday;
    private Double price;
    }
    
    // @JsonIgnore加在属性上面,使序列化时忽略该字段
    {"password":"123456","birthday":1533888026016,"price":0.6}

    4. @JsonFormat 用在Date时间类型属性上面,用于序列化时间为需要的格式

    public class Pet {
    private String username;
    private String password;
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
    private Date birthday;
    private Double price;
    }
    
    // @JsonFormat加在属性上面,用于jackson对时间格式规定,注意要指定中国时区为+8
    {"username":"哈哈","password":"123456","birthday":"2018-08-10 16:17:51","price":0.6}

    5. @JsonInclude 用在类上面,用于声明在序列化时忽略一些没有意义的字段,例如:属性为NULL的字段

    @JsonInclude(Include.NON_NULL)
    public class Pet {
    private String username;
    private String password;
    private Date birthday;
    private Double price;
    }
    
    // @JsonInclude加在类上面,jackson序列化时会忽略无意义的字段,例如username和price是空值,那么就不序列化这两个字段
    {"password":"123456","birthday":1533890045175}

    6. @JsonSerialize 用在类或属性上面,用于指定序列化时使用的JsonSerialize类

    一般会使用自定义的序列化器,例如自定义MyJsonSerializer,用来处理Double类型序列化时保留两位小数,就非常好用

    public class MyJsonSerializer extends JsonSerializer<Double>{
    @Override
    public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers)
    throws IOException, JsonProcessingException {
     if (value != null)
        gen.writeString(BigDecimal.valueOf(value).
                setScale(2, BigDecimal.ROUND_HALF_UP).toString()); // ROUND_HALF_UP四舍五入
      }
    }

    使用方式

    public class Pet {
    private String username;
    private String password;
    private Date birthday;
    @JsonSerialize(using=MyJsonSerializer.class)
    private Double price;
    }
    
    // 指定序列化price属性时使用自定义MyJsonSerializer,对Double类型进行自定义处理,保留两位小数
    
    {"username":"哈哈","password":"123456","birthday":1533892290795,"price":"0.60"}

    Jackson和SpringMVC整合使用

    jackson作为springMVC官方推荐使用MessageConverter工具,并成为springMVC默认的MessageConverter工具,因此在springMVC中使用jackson非常简单,springMVC会在需要json格式的response响应时,扫描项目中是否拥有jackson的相关类库,如果拥有,那么默认就会使用jackson进行消息转换,如果没有,就会报异常。无需手动配置jackson。

    当然也是可以手动配置的,在spring-application.xml中加入下面配置:

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    该配置是默认配置,默认不配置就行,那么如果需要个性化的配置,就需要对MappingJackson2HttpMessageConverter进行设置,例如对jackson时间格式的输出进行全局修改,进行如下配置

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <constructor-arg name="objectMapper">
                    <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                        <property name="dateFormat">
                            <bean class="java.text.SimpleDateFormat">
                                <constructor-arg index="0" value="yyyy-MM-dd HH:mm:ss" />
                                <constructor-arg index="1" value="#{T(java.util.Locale).SIMPLIFIED_CHINESE}" />
                                <property name="timeZone" value="GMT+8" />
                            </bean>
                        </property>
                    </bean>
                </constructor-arg>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    个性化定制对于项目中使用jackson非常重要,实际使用中可以根据需求进行扩展,对MappingJackson2HttpMessageConverter进行设置。

    jackson和spring-boot整合使用

    同样,jackson也是作为spring-boot的默认MessageConverter工具,他被包含在spring-boot-starter-web依赖中,这里主要说明spring-boot如何对jackson进行个性化配置,重写WebMvcConfigurerAdapter类的configureMessageConverters方法即可,如下

    @Configuration
    public class WebConfig extends WebMvcConfigurerAdapter {
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            ObjectMapper objectMapper = new ObjectMapper();
            // 设置Date类型字段序列化方式
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.SIMPLIFIED_CHINESE));
            
            // 指定BigDecimal类型字段使用自定义的CustomDoubleSerialize序列化器
            SimpleModule simpleModule = new SimpleModule();
            simpleModule.addSerializer(BigDecimal.class, new CustomDoubleSerialize());
            objectMapper.registerModule(simpleModule);
            
            MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper);
            converters.add(converter);
        }
    }

    可以看出,spring-boot对于jackson的使用更加灵活。


















     
     
     


  • 相关阅读:
    广陵基地输电线路实训场
    广陵基地配电网综合实训室
    广陵基地电缆实训室
    Windows Phone 9再见了!
    Windows Phone 8初学者开发—第23部分:测试并向应用商店提交
    Windows Phone 8初学者开发—第22部分:用演示图板创建卷盘的动画
    JDBC数据类型
    Java-BlockingQueue的使用
    苹果下如果安装nginx,给nginx安装markdown第三方插件
    苹果电脑包管理
  • 原文地址:https://www.cnblogs.com/dyh004/p/12192408.html
Copyright © 2011-2022 走看看