zoukankan      html  css  js  c++  java
  • Json中相关注解解释说明

      @JsonProperty用法:

    @JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,@JsonProperty(“name”),

    这样得到结果

    {“name”:“张三”}

      @jsonSerialize用法:

    实际开发中,我们一定遇到过这样的问题:前端显示和后台存储数据单位不统一,而且各有各自的理由,统一不了,那就转换吧。

    每次返回给前端时再转换一遍,返回给前端的json数据,在后端里定义的往往是一个对象,如何做到优雅的转换呢?只需两步

    1. 写一个负责转换的类,里面写好规则

    2. 在实体类上需要装换的字段上加上注解

    这样就成功将Date类型转换为Long类型输出了。

    @JsonSerialize注解,主要用于数据转换,该注解作用在该属性的getter()方法上。

      @JsonIgnoreProperties

    此注解是类注解,作用是json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响。

    写法将此标签加在model 类的类名上 ,可以多个属性也可以单个属性

    //生成json时将name和age属性过滤

    @JsonIgnoreProperties({"name"},{"age"})

    public class  user {

    private  String name;

    private int age;

    }


      @JsonIgnore

    此注解用于属性或者方法上(最好是属性上),作用和上面的@JsonIgnoreProperties一样。

    生成json 时不生成age 属性

    public class user {

    private String name;

    @JsonIgnore

    private int age;

    }

      @JsonFormat

    此注解用于属性或者方法上(最好是属性上),可以方便的把Date类型直接转化为我们想要的模式,比如@JsonFormat(pattern = “yyyy-MM-dd HH-mm-ss”)

      @Transient

    ORM框架将忽略该属性;

    如果一个属性并非数据库表的字段映射,就务必将其标示为@Transient,否则ORM框架默认其注解为@Basic;

     

      @JsonInclude

    前端的同事要求说尽量不要有null,可有为空串“” 或者 0 或者 [], 但尽量不要nul,

    所以@JsonInclude(Include.NON_NULL) 这个注解放在类头上就可以解决。 实体类与json互转的时候 属性值为null的不参与序列化

      

    import com.fasterxml.jackson.annotation.JsonInclude;
    import com.fasterxml.jackson.annotation.JsonInclude.Include;

    @JsonInclude(Include.NON_NULL)
    public class WithdrawDetail implements Serializable {

    }

      实际效果

    全局配置

    springMVC.xml

    <!-- 默认的注解映射的支持 比如requestMapper之类的 -->
    <mvc:annotation-driven>
    <mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <property name="objectMapper">
    <bean class="com.fasterxml.jackson.databind.ObjectMapper">
    <property name="serializationInclusion"> 
    <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value> 
    </property>
    </bean>
    </property>
    </bean>
    </mvc:message-converters>
    </mvc:annotation-driven>

    --------------spring boot 的配置

    只在配置文件加上一个配置

    spring.jackson.default-property-inclusion=non_null

  • 相关阅读:
    17. Letter Combinations of a Phone Number
    16. 3Sum Closest
    15. 3Sum
    14. Longest Common Prefix
    13. Roman to Integer
    12. Integer to Roman
    11. Container With Most Water
    10. Regular Expression Matching
    9. Palindrome Number
    8. String to Integer (atoi)
  • 原文地址:https://www.cnblogs.com/panbingqi/p/11212194.html
Copyright © 2011-2022 走看看