千家信息网

Json的注解有哪些

发表于:2025-02-04 作者:千家信息网编辑
千家信息网最后更新 2025年02月04日,Json的注解有哪些,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。1.@JsonIgnoreProperties在类上注解哪些属性不
千家信息网最后更新 2025年02月04日Json的注解有哪些

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

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

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

2.@JsonIgnore
属性上忽略

@Datapublic class Person {   private String hello;  @JsonIgnore  private String word;}

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

@Datapublic 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方法上,也可以直接加在属性上

@Datapublic class Person {   private String hello;  private String word;  @JsonSerialize(using = CustomDoubleSerialize.class)  private Double money;}public class CustomDoubleSerialize extends JsonSerializer {     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方法上,也可以直接加在属性上

@Datapublic class Person {   private String hello;  private String word;   @JsonDeserialize(using = CustomDateDeserialize.class)  private Date time;}public class CustomDateDeserialize extends JsonDeserializer {        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 不序列化

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

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

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


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

使用变量修饰符 transient

这里打印password 的值是为 空的

使用关键字 static

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

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

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

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

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

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

0