温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Json的注解有哪些

发布时间:2021-10-20 09:26:17 来源:亿速云 阅读:114 作者:柒染 栏目:大数据

Json的注解有哪些,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

1.@JsonIgnoreProperties
在类上注解哪些属性不用参与序列化和反序列化

@Data
@JsonIgnoreProperties(value = { "word" })  
public class Person { 
  private String hello;
  private String word;
}

2.@JsonIgnore
属性上忽略

@Data
public class Person { 
  private String hello;
  @JsonIgnore
  private String word;
}

3.@JsonFormat
格式化序列化后的字符串

@Data
public class Person{
  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm",timezone = "GMT+8")
  private Date time;
  private String hello;
  private String word;
}

4.@JsonSerialize
序列化的时候通过重写的方法,可以加在get方法上,也可以直接加在属性上

@Data
public class Person { 
  private String hello;
  private String word;
  @JsonSerialize(using = CustomDoubleSerialize.class)
  private Double money;
}

public class CustomDoubleSerialize extends JsonSerializer<Double> {  
   private DecimalFormat df = new DecimalFormat("#.##"); 
   @Override    
   public void serialize(Double value, JsonGenerator jgen, SerializerProvider provider) throws IOException,            JsonProcessingException { 
       jgen.writeString(df.format(value));    
   }
}

5.@JsonDeserialize
反序列化的时候通过重写的方法,可以加在set方法上,也可以直接加在属性上

@Data
public class Person { 
  private String hello;
  private String word; 
  @JsonDeserialize(using = CustomDateDeserialize.class)
  private Date time;
}

public class CustomDateDeserialize extends JsonDeserializer<Date> {  
  
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
  
    @Override  
    public Date deserialize(JsonParser jp, DeserializationContext ctxt)  
            throws IOException, JsonProcessingException {  
  
        Date date = null;  
        try {  
            date = sdf.parse(jp.getText());  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }  
        return date;  
    }  
}

5.@JsonInclude
Include.Include.ALWAYS 默认
Include.NON_DEFAULT 属性为默认值不序列化
Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化(想前端传数据的时候list为空的时候不进行序列化)
Include.NON_NULL 属性为NULL 不序列化

@Data
public class OrderProcessTime { 
    @JsonInclude(JsonInclude.Include.ALWAYS)
    private Date plan;
}

6.@JsonProperty
用于表示Json序列化和反序列化时用到的名字,例如一些不符合编程规范的变量命名

@Data
public class Person { 
  private String hello;
  private String word; 
  private Date time;
  @JsonProperty(value = "DeliveryTime")
  private Integer deliveryTime;
}


7.Java序列化排除指定字段

使用变量修饰符  transient

Json的注解有哪些

这里打印password 的值是为 空的

使用关键字 static

Json的注解有哪些

第二种这个很容易产生误解,content在输出的时候还是有数据的,

反序列化输入的值是  “只是之前的值” ,之后打印的值虽然也是看到 “只是之前的值”,其实这个不是序列化那个的值的

如果不理解,可以从新设置一个content的值

MsgInfo.setContent("这是修改的");

在反序列化打印处理后,会看到输出的值是刚刚设置的值 “这是修改的”
 

关于Json的注解有哪些问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI