赞
踩
将不同的数据格式与JSON格式进行转换需要依赖第三方包
JSON //json官方提供的
FastJson //阿里巴巴提供
Jackson //springboot启动包自带
GSON //Google提供的
hutool json //hutool 工具
第三方包有很多,选择一种就好了,这里选择Jackson
①导入依赖
Jackson 解析JSON,SpringMVC内置的解析器就是这个
spring-boot-starter-web启动包内嵌了Jackson 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.16</version>
</dependency>
或者也可以自己导入依赖包
maven依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
②Jackson包中ObjectMapper类介绍
1、常用方法1:readValue() 方法可以进行 JSON 的反序列化操作,就是将其他格式数转为Java对象
2、常用方法2:writeValue() 方法可以进行 JSON 的序列化操作,就是将 Java 对象转换成 JSON 字符串
Java中看到的JSON字符经常带有斜杠,其实是转义符,例如:
\r 将光标定位到当前行的开头,不会跳到下一行。
\n 换到下一行的开头。
\t 制表符,将光标移到下一个制表符的位置,就像在文档中用Tab键一样。
\\ 表示反斜杠字符,由于在Java代码中的反斜杠(\)是转义字符,多加一个反斜杠就代表其本身
\"
表示双引号字符,Java代码中双引号表示字符串的开始和结束,包含在字符串中的双引号需要使用 \
进行转义
String str = "{\"name\":\"bbb\",\"id\":\"1234\"}"
其实是 str = {"name":"bbb","id":"1234"}
首先我有个User类
package com.test.springboot.model;
public class User {
private String name;
private int age;
private List<String> skillsList;
//省略getter setter toString
使用方法:objectMapper.writeValueAsString(类名);
public static void objectToJson() {
User user = new User();
user.setName("bbb");
user.setAge(18);
user.setSkillsList(Arrays.asList("java", "python"));
// 创建ObjectMapper对象
ObjectMapper objectMapper = new ObjectMapper();
String json = null;
try {
// 将对象转换为JSON字符串
json = objectMapper.writeValueAsString(user);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//{"name":"bbb","age":18,"skillsList":["java","python"]}
System.out.println(json);
}
public void listToJson() {
List<String> list = new ArrayList<>();
list.add("item1");
list.add("item2");
list.add("item3");
System.out.println("list---"+list);
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(list);
System.out.println("json---"+json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
public void mapToJson() {
Map<String, String> map = new HashMap<>();
map.put("名字", "薄饼");
map.put("年龄", "12");
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(map);
System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
public void mapListToJson() {
//rootMap集合存储信息
Map<String, Object> rootMap = new HashMap<>();
rootMap.put("notificationType", "call_service");
//serviceMap集合存储信息
Map<String, Object> serviceMap = new HashMap<>();
serviceMap.put("appKey", "Data.appKey");
//paraList中存储多个alaMap
List<Map<String, Object>> paraList = new ArrayList<>();
Map<String, Object> alaMap= new HashMap<>();
alarmMap.put("a", "zh110");
alarmMap.put("b", "zh120");
alarmMap.put("notify", "[Info1|Info2|Info3]");
paraList.add(alaMap);
serviceMap.put("notifications", paraList);
rootMap.put("call_service", serviceMap);
ObjectMapper mapper = new ObjectMapper();
try {
String rootMapJson = mapper.writeValueAsString(rootMap);
System.out.println(rootMapJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
首先我有个User类
package com.test.springboot.model;
public class User {
private String name;
private int age;
private List<String> skillsList;
//省略getter setter toString
使用objectMapper.readValue(json, User.class);方法,前面传入json字符串,后面是类
//json字符串信息 写入(转为) 对象
public static void jsonToObject(){
String json = "{\"name\":\"bbb\",\"age\":18,\"skillsList\":[\"java\",\"python\",\"php\"]}";
ObjectMapper objectMapper = new ObjectMapper();
User user = null;
try {
user = objectMapper.readValue(json, User.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//User(name=bbb, age=18, skillsList=[java, python, php])
System.out.println(user);
//{"name":"bbb","age":18,"skillsList":["java","python","php"]}
System.out.println(json);
}
001-test/src下新建json文件,内容如下
{
"name" : "bbb",
"age" : 18,
"skillsList" : [
"java",
"python"
]
}
如图:
使用readValue方法
public static void jsonFileToObject() {
File file = new File("001-test/src/test.json");
ObjectMapper objectMapper = new ObjectMapper();
User user = null;
try {
user = objectMapper.readValue(file, User.class);
} catch (IOException e) {
e.printStackTrace();
}
//User(name=bbb, age=18, skillsList=[java, python])
System.out.println(user);
}
//通过字节输入流FileInputStream 读取json文件后,再转为对象
public static void jsonFileInputStrToObject() {
FileInputStream input = null;
try {
input = new FileInputStream("001-test/src/test.json");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ObjectMapper objectMapper = new ObjectMapper();
User user = null;
try {
user = objectMapper.readValue(input, User.class);
} catch (IOException e) {
e.printStackTrace();
}
//User{name='bbb', age=18, skillsList=[java, python]}
System.out.println(user);
}
//JSON字符串 转为 Map
public static void jsonToMap() {
String json = "{\"name\":\"bbb\",\"age\":18,\"skillsList\":[\"java\",\"python\",\"php\"]}";
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> objectMap = null;
try {
objectMap = objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {
});
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//{name=bbb, age=18, skillsList=[java, python, php]}
System.out.println(objectMap);
//bbb
System.out.println(objectMap.get("name"));
}
readValue方法
public static void jsonArrToObject() {
String json = "[{\"name\":\"bbb\",\"age\":18,\"skillsList\":[\"java\",\"python\"]}," +
"{\"name\":\"aaa\",\"age\":15,\"skillsList\":[\"唱跳\",\"rap\"]}]";
ObjectMapper objectMapper = new ObjectMapper();
User[] user = new User[0];
try {
user = objectMapper.readValue(json, User[].class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//User{name='bbb', age=18, skillsList=[java, python]}
//User{name='aaa', age=15, skillsList=[唱跳, rap]}
for (User user1 : user) {
System.out.println(user1);
}
}
readValue方法
public static void jsonListToList() {
String json = "[{\"name\":\"bbb\",\"age\":18,\"skillsList\":[\"java\",\"python\"]}," +
"{\"name\":\"aaa\",\"age\":15,\"skillsList\":[\"唱跳\",\"rap\"]},"+
"{\"name\":\"ccc\",\"age\":10,\"skillsList\":[\"biu\",\"pon\"]}]";
ObjectMapper objectMapper = new ObjectMapper();
List<User> list = null;
try {
list = objectMapper.readValue(json, new TypeReference<List<User>>(){
});
} catch (JsonProcessingException e) {
e.printStackTrace();
}
// User{name='bbb', age=18, skillsList=[java, python]}
// User{name='aaa', age=15, skillsList=[唱跳, rap]}
// User{name='ccc', age=10, skillsList=[biu, pon]}
for (User user1 : list) {
System.out.println(user1);
}
}
如果 JSON出现了 Java 类中不存在的属性,转 Java 对象时会报com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException
异常。
使用configure方法,设置false来忽略
public static void jsonIgn() {
String json = "{\"需要忽略的\":\"需要忽略\",\"name\":\"bbb\",\"age\":18,\"skillsList\":[\"java\",\"python\"]}";
ObjectMapper objectMapper = new ObjectMapper();
//忽略字段设置
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
User user=null;
try {
user = objectMapper.readValue(json, User.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//User{name='bbb', age=18, skillsList=[java, python]}
System.out.println(user);
}
①添加数据绑定支持包依赖
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.13.3</version>
</dependency>
②在类中使用注解@JsonFormat
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order {
private Integer id;
@JsonFormat(pattern = "yyyy年MM月dd日 HH时mm分ss秒",timezone = "Asia/Shanghai")
private Date date;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "Asia/Shanghai")
private LocalDateTime localDateTime;
}
③定义 ObjectMapper 时通过 findAndRegisterModules() 方法来注册依赖。然后再互相转换
//Jackson 日期格式化
public class JsonToJava9 {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper().findAndRegisterModules();
Order order = new Order();
order.setId(1);
order.setDate(new Date());
order.setLocalDateTime(LocalDateTime.now());
//将java转换成json字符串
String json = objectMapper.writeValueAsString(order);
//{"id":1,"date":"2023年07月28日 15时14分01秒","localDateTime":"2023-07-28 15:14:01"}
System.out.println(json);
//将json字符串转换成java对象
Order orderObject = objectMapper.readValue(json, Order.class);
//Order(id=1, date=Fri Jul 28 15:15:59 CST 2023, localDateTime=2023-07-28T15:15:59)
System.out.println(orderObject);
}
}
使用 @JsonIgnore可以忽略某个 Java 对象中的属性,它将不参与 JSON 的序列化与反序列化
使用 @JsonGetter可以在对 Java 对象进行 JSON 序列化时自定义属性名称。写在getter方法上
@JsonGetter(value = "catName")
public String getName() {
return name;
}
输出结果,name 已经设置成了 catName:
{"age":2,"catName":"Tom"}
使用 @JsonSetter可以在对 JSON 进行反序列化时设置 JSON 中的 key 与 Java 属性的映射关系。用在属性上
比如我json中是这样catName
String json = "{\"age\":2,\"catName\":\"Tom\"}";
为了我这个name能对应上json内容,通过注解设置成catName
@JsonSetter(value = "catName")
public void setName(String name) {
this.name = name;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。