Jackson_annotations注解使用

news/2025/1/11 14:53:40/

1、@JsonIdentityInfo 英文说明:

1、@JsonIdentityInfo is used when objects have parent child relationship. @JsonIdentityInfo is used to indicate that object identity will be used during serialization/de-serialization.

2、中文翻译:@JsonIdentityInfo 在对象具有父子关系时使用。@JsonIdentityInfo 用于指示在序列化/反序列化期间将使用对象标识。

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;public class JacksonTester {public static void main(String args[]) throws IOException, ParseException{ObjectMapper mapper = new ObjectMapper();     Student student = new Student(1,13, "Mark");Book book1 = new Book(1,"Learn HTML", student);Book book2 = new Book(2,"Learn JAVA", student);student.addBook(book1);student.addBook(book2);String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(book1);System.out.println(jsonString);}
}
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
class Student { public int id;public int rollNo;public String name;public List<Book> books;Student(int id, int rollNo, String name){this.id = id;this.rollNo = rollNo;this.name = name;this.books = new ArrayList<Book>();}public void addBook(Book book){books.add(book);}
}
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
class Book{public int id;public String name;Book(int id, String name, Student owner){this.id = id;this.name = name;this.owner = owner;}public Student owner;
}输出: 
{
"id" : 1,
"name" : "Learn HTML",
"owner" : {
"id" : 1,
"rollNo" : 13,
"name" : "Mark",
"books" : [
1, {
"id" : 2,
"name" : "Learn JAVA",
"owner" : 1
}
]
}
}

2、@JsonAnyGetter

1、英文
allows a getter method to return Map which is then used to serialize the additional properties of JSON in the similar fashion as other properties.

2、翻译
允许一个 getter 方法返回 Map 然后用于以与其他属性类似的方式序列化 JSON 的其他属性。

  • 没有@JsonAnyGetter 的示例
import java.io.IOException; 
import java.util.HashMap; 
import java.util.Map; 
import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTester { public static void main(String args[]){ObjectMapper mapper = new ObjectMapper(); try{Student student = new Student(); student.add("Name", "Mark"); student.add("RollNo", "1"); String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); } catch (IOException e) { e.printStackTrace(); }   }
}
class Student {private Map<String, String> properties; public Student(){ properties = new HashMap<>(); } public Map<String, String> getProperties(){ return properties; } public void add(String property, String value){ properties.put(property, value); } 
}
  • 输出结果
{"properties" : {"RollNo" : "1","Name" : "Mark"} 
}
  • @JsonAnyGetter 示例
import java.io.IOException; 
import java.util.HashMap; 
import java.util.Map; 
import com.fasterxml.jackson.annotation.JsonAnyGetter; 
import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTester {public static void main(String args[]){ObjectMapper mapper = new ObjectMapper();try{Student student = new Student(); student.add("Name", "Mark"); student.add("RollNo", "1"); String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); }catch (IOException e) {e.printStackTrace();} }
}
class Student {private Map<String, String> properties;public Student(){properties = new HashMap<>();}@JsonAnyGetterpublic Map<String, String> getProperties(){return properties;}public void add(String property, String value){properties.put(property, value);}
}
  • 输出
    {
    “RollNo” : “1”,
    “Name” : “Mark”
    }

3、@JsonGetter

  • 英文:
    @JsonGetter allows a specific method to be marked as getter method.
  • 翻译:
    @JsonGetter允许将特定方法标记为 getter 方法。
  • 没有@JsonGetter 的示例
import java.io.IOException; 
import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTester {public static void main(String args[]){ObjectMapper mapper = new ObjectMapper();try {Student student = new Student("Mark", 1);String jsonString = mapper .writerWithDefaultPrettyPrinter().writeValueAsString(student);System.out.println(jsonString);}catch (IOException e) {e.printStackTrace();}}
}
class Student {private String name;private int rollNo;public Student(String name, int rollNo){this.name = name;this.rollNo = rollNo;}  public String getStudentName(){return name;} public int getRollNo(){return rollNo;}
}
  • 输出
{
"studentName" : "Mark",
"rollNo" : 1
}
  • @JsonGetter 的示例
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.annotation.JsonGetter; public class JacksonTester {public static void main(String args[]){ ObjectMapper mapper = new ObjectMapper(); try {Student student = new Student("Mark", 1);    String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); } catch (IOException e) { e.printStackTrace();  }   }
}
class Student {private String name;private int rollNo;public Student(String name, int rollNo){this.name = name;this.rollNo = rollNo;}@JsonGetterpublic String getStudentName(){return name;}public int getRollNo(){return rollNo;}
}
  • 输出
{
"name" : "Mark",
"rollNo" : 1
}

4、@JsonPropertyOrder

  • 英文:allows a specific order to be preserved while serializing a JSON object.
  • 翻译:允许在序列化 JSON 对象时保留特定顺序。
  • 没有@JsonPropertyOrder 的示例
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;public class JacksonTester {public static void main(String args[]){ObjectMapper mapper = new ObjectMapper();try {Student student = new Student("Mark", 1);String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);System.out.println(jsonString);}catch (IOException e) {e.printStackTrace();}}
}
class Student {private String name;private int rollNo;public Student(String name, int rollNo) {this.name = name;this.rollNo = rollNo;}public String getName(){return name;}public int getRollNo(){return rollNo; }
}
  • 输出
{
"name" : "Mark",
"rollNo" : 1
}
  • 示例@JsonPropertyOrder
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;public class JacksonTester {public static void main(String args[]){ObjectMapper mapper = new ObjectMapper();try {Student student = new Student("Mark", 1);String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);System.out.println(jsonString);}catch (IOException e) {e.printStackTrace();}}
}
@JsonPropertyOrder({ "rollNo", "name" })
class Student {private String name; private int rollNo; public Student(String name, int rollNo){ this.name = name; this.rollNo = rollNo; }  public String getName(){ return name; } public int getRollNo(){ return rollNo; }  
}
  • 输出
{
"name" : "Mark",
"rollNo" : 1
}

5、@JsonRawValue

  • 英文:@JsonRawValue allows to serialize a text without escaping or without any decoration.
  • 翻译:允许在不转义或不进行任何修饰的情况下序列化文本。
  • 没有@JsonRawValue 的示例
import java.io.IOException; 
import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTester {public static void main(String args[]){ObjectMapper mapper = new ObjectMapper();try {Student student = new Student("Mark", 1, "{\"attr\":false}");    String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); }catch (IOException e) { e.printStackTrace(); }   }
}
class Student { private String name; private int rollNo; private String json;  public Student(String name, int rollNo, String json){this.name = name; this.rollNo = rollNo; this.json = json; }  public String getName(){ return name; } public int getRollNo(){ return rollNo; } public String getJson(){ return json; }  
}
  • 输出
{
"name" : "Mark",
"rollNo" : 1,
"json" : {\"attr\":false}
}
  • @JsonRawValue 示例
import java.io.IOException; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.annotation.JsonRawValue; public class JacksonTester {public static void main(String args[]){ObjectMapper mapper = new ObjectMapper(); try {Student student = new Student("Mark", 1, "{\"attr\":false}");    String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); }catch (IOException e) { e.printStackTrace(); }   }
}
class Student { private String name; private int rollNo;@JsonRawValue  private String json;  public Student(String name, int rollNo, String json) {this.name = name; this.rollNo = rollNo; this.json = json; }  public String getName(){ return name; } public int getRollNo(){ return rollNo; } public String getJson(){ return json; }  
} 
  • 输出
{
"name" : "Mark",
"rollNo" : 1,
"json" : {"attr":false}
}
  • 6、@JsonValue
  • 英文: @JsonValue allows to serialize an entire object using its single method.
  • 翻译: @JsonValue允许使用其单一方法序列化整个对象
  • 示例@JsonValue
import java.io.IOException; 
import com.fasterxml.jackson.annotation.JsonValue; 
import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTester {public static void main(String args[]){ObjectMapper mapper = new ObjectMapper(); try { Student student = new Student("Mark", 1);    String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); }catch (IOException e) { e.printStackTrace(); }   }
}
class Student {private String name;private int rollNo;public Student(String name, int rollNo){this.name = name;this.rollNo = rollNo;}public String getName(){return name;} public int getRollNo(){return rollNo;}@JsonValuepublic String toString(){return "{ name : " + name + " }";}
  • 输出:
"{ name : Mark }"

7、JsonRootName

  • 英文:@JsonRootName allows to have a root node specified over the JSON. We need to enable wrap root value as well.
  • 翻译: @JsonRootName允许在 JSON 上指定一个根节点。我们还需要启用包装根值。
  • Example @JsonRootName
import java.io.IOException; 
import com.fasterxml.jackson.annotation.JsonRootName; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.SerializationFeature; public class JacksonTester {public static void main(String args[]){ ObjectMapper mapper = new ObjectMapper(); try {Student student = new Student("Mark", 1);  mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); }catch (IOException e) { e.printStackTrace(); }   }
}
@JsonRootName(value = "student") 
class Student {private String name; private int rollNo; public Student(String name, int rollNo){ this.name = name; this.rollNo = rollNo; }  public String getName(){ return name; } public int getRollNo(){ return rollNo; }  
}
  • 输出
{
"student" : {
"name" : "Mark",
"rollNo" : 1
}
}

8、@JsonSerialize

  • 英文: @JsonSerialize is used to specify custom serializer to marshall the json object.
  • 翻译: @JsonSerialize用于指定自定义序列化程序来编组 json 对象。
  • @JsonSerialize 示例
import java.io.IOException; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; import com.fasterxml.jackson.core.JsonGenerator; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.SerializerProvider; 
import com.fasterxml.jackson.databind.annotation.JsonSerialize; 
import com.fasterxml.jackson.databind.ser.std.StdSerializer; public class JacksonTester {public static void main(String args[]) throws ParseException {ObjectMapper mapper = new ObjectMapper(); SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); try {Student student = new Student("Mark", 1, dateFormat.parse("20-11-1984")); String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); } catch (IOException e) { e.printStackTrace(); }   }
}
class Student {private String name; private int rollNo; @JsonSerialize(using = CustomDateSerializer.class) private Date dateOfBirth; public Student(String name, int rollNo, Date dob){ this.name = name; this.rollNo = rollNo; this.dateOfBirth = dob; }public String getName(){return name;}public int getRollNo(){return rollNo; }public Date getDateOfBirth(){ return dateOfBirth; }
}
class CustomDateSerializer extends StdSerializer<Date> {private static final long serialVersionUID = 1L; private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");public CustomDateSerializer() { this(null); } public CustomDateSerializer(Class<Date> t) { super(t); } @Override public void serialize(Date value, JsonGenerator generator, SerializerProvider arg2) throws IOException { generator.writeString(formatter.format(value)); } 
}
  • 输出
{
"name" : "Mark",
"rollNo" : 1,
"dateOfBirth" : "20-11-1984"
}

http://www.ppmy.cn/news/10447.html

相关文章

计算机网络复习之网络层

文章目录数据报与虚电路服务的对比IP 协议IP数据报格式IP地址NAT&#xff08;网络地址转换&#xff09;子网划分和子网掩码在支持子网划分的因特网中&#xff0c;路由器如何转发IP数据报无分类编制CIDR构成超网RIP协议OSPF协议ARP协议ICMP协议Ping和Traceroute参考路由选择是网…

C库函数:time.h

time.h C 标准库 – <time.h> | 菜鸟教程 (runoob.com) 库变量 下面是头文件 time.h 中定义的变量类型&#xff1a; 序号变量 & 描述1size_t 是无符号整数类型&#xff0c;它是 sizeof 关键字的结果。2clock_t 这是一个适合存储处理器时间的类型。3time_t is 这是一…

Flow 转 LiveData 后数据丢了,肿么回事?

翻译自&#xff1a; https://arkadiuszchmura.com/posts/be-careful-when-converting-flow-to-livedata/ 前言 最近我在负责一段代码库&#xff0c;需要在使用 Flow 的 Data 层和仍然依赖 LiveData 暴露 State 数据的 UI 层之间实现桥接。好在 androidx.lifecycle 框架已经提供…

【Kotlin】空安全 ④ ( 手动空安全管理 | 空合并操作符 ?: | 空合并操作符与 let 函数结合使用 )

文章目录一、空合并操作符 ?:二、空合并操作符与 let 函数结合使用一、空合并操作符 ?: 空合并操作符 ?: 用法 : 表达式 A ?: 表达式 B如果 表达式 A 的值 不为 null , 则 整个表达式的值 就是 表达式 A 的值 ; 如果 表达式 A 的值 为 null , 则 整个表达式的值 就是 表达…

华为OD机试 - 微服务的集成测试

题目描述 现在有n个容器服务,服务的启动可能有一定的依赖性(有些服务启动没有依赖),其次服务自身启动加载会消耗一些时间。 给你一个nxn的二维矩阵useTime,其中useTime[i][i]=10表示服务i自身启动加载需要消耗10s, useTime[i][j] = 1表示服务i启动依赖服务j启动完成,us…

剑指 Offer 56 - I. 数组中数字出现的次数

题目要求时间复杂度是O(n)&#xff0c;空间复杂度是O(1)。 异或可以将两个只出现一次的数筛选出来&#xff0c;之后再把这两个数分到两组中&#xff0c;并且将相同的数分到同一组&#xff0c;两组分别异或就能求出两个数。 异或规则是不相同为1&#xff0c;相同为0 所以利用a^…

vitepress(三):自动生成目录

上一节我们将自己的网站发布到了git pages上&#xff0c;但是现在我们需要每次更新一篇文章就重写一次目录&#xff0c;操作上十分的繁琐和不方便&#xff0c;所以我们需要一个方法去自动生成我们的侧边栏结构&#xff0c;方便我们每次只需要更新我们的项目即可。这里我们要知道…

机器学习(4)——周志华

归纳偏好 若非必要&#xff0c;勿增实体 若多个算法都能解决同一个问题&#xff0c;则选取最简单的算法 当前什么样的偏好与问题更匹配&#xff0c;必须对问题有一个清楚的认识