其他分享
首页 > 其他分享> > @JsonField和@JsonProperty的使用和区别

@JsonField和@JsonProperty的使用和区别

作者:互联网

@JsonField

JsonField是位于fastjson包下的,实体类序列化为json字符串的时候,此类的原字段,序列化为json中的规定的字段

配合JSON.toJSONString(object),能将实体类转换成json字符串,配合JSON.parseObject(str,Object.class),能将字符串转换成实体类

添加依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

实体类

public class Person{
  @JsonField(name = "name")
  private String finalName;
  
  public String getFinalName() {
        return FinalName;
  }

  public void setFinalName(String finalName) {
      FinalName = finalName;
  }
}

测试类

public class Test{
  public static void main(String[] args){
    Person person = new Person();
    person.setFinalName("张三");
    System.out.println(JSON.toJSONString(person));

    String str = "{\"name\":\"张三\"}";
    String str2 = "{\"finalName\":\"张三\"}";
    System.out.println(JSON.parseObject(str,Person.class));
    System.out.println(JSON.parseObject(str2,Person.class));
  }
}
image-20211118114557641

@JsonProperty

JsonProperty是位于jackson包里的,配合ObjectMapper的writeValueAsString(object)方法可以将实体类转换为字符串,配合ObjectMapper的readValue(str)可以将字符串转换为实体类

添加依赖

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

实体类

public class Person{
  @JsonProperty(value = "name")
  private String finalName;
  
  public String getFinalName() {
        return FinalName;
  }

  public void setFinalName(String finalName) {
      FinalName = finalName;
  }
  
  @Override
  public String toString() {
      return "Person{" +
              "FinalName='" + FinalName + '\'' +
              '}';
  }
}

测试类

public class Test{
  public static void main(String[] args){
    Person person = new Person();
    person.setFinalName("张三");
    try{
      System.out.println(new ObjectMapper().writeValueAsString(person));
    } catch (JsonProcessingException e){
      e.printStackTrace();
    }
    
    String str = "{\"name\":\"张三\"}";
    try{
      System.out.println(new ObjectMapper().readValue(str, Person.class).toString());
    } catch (IOException e){
      e.printStackTrace();
    }
  }
}
image-20211118113350062

标签:JsonProperty,实体类,String,区别,class,finalName,Person,JsonField,public
来源: https://www.cnblogs.com/jtxw/p/15571660.html