日志概述
在日常实践中通常会对JSON数据和Java对象进行相互转换,转换需要用到JSON解析器,常见的解析器如下:
- Jsonlib(JSON官方)
- Gson(Google)
- Jackson(Spring官方)
- Fastjson(Alibaba)
作为 Spring MVC / SpringBoot 技术栈 开发的话,用默认的Jackson
是最好的!
数据量少时:Gson快
数据量多时:FastJson快
数据量无论多少:Jackson最稳定
Jackson
SpringBoot2 中的 web starter 中就内置了 jackson 三个jar依赖
Maven构建地址 | Github地址
目前最新版为 2.12.3 其中三个jar 各自大小为
- jackson-core 314Kb
- jackson-databind 1.3Mb
- jackson-annotations 65Kb
快速入门
引入依赖
pom.xml
springboot\springmvc内置,不需要在引入
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.12.3</version>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.12.3</version>
</dependency>
<!-- 注意:如没有用到注解去配置,可不用引入此依赖 -->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.12.3</version>
</dependency>
代码测试
Java代码:
package com.demo;import com.demo.entity.User;
import com.demo.mapper.UserMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@SpringBootTest
class SpringbootalinbabaSsmStart01ApplicationTests {private static final Logger LOGGER = LoggerFactory.getLogger(SpringbootalinbabaSsmStart01ApplicationTests.class);@Autowiredprivate UserMapper userMapper;@Testpublic void test1() {List<User> userList = userMapper.queryAllUser();for (User user : userList) {LOGGER.info("数据为:{}", user);}}@Testpublic void test2() throws IOException {//创建对象User user = new User();user.setId(0L);user.setUsername("张三");user.setEmail("123@qq.com");user.setPassword("123");user.setPhoneNum("456");User[] users = {user,new User(2L,"李四","邮箱","密码","电话")};ArrayList<String> list = new ArrayList<>();list.add("苹果");list.add("橘子");HashMap<String, Object> map = new HashMap<>();map.put("name", "张三");map.put("age", 20);//创建jackson的核心对象ObjectMapper objectMapper = new ObjectMapper();//java对象(包括list、map)转json字符串String pStr1 = objectMapper.writeValueAsString(user);String pStr2 = objectMapper.writeValueAsString(list);String pStr3 = objectMapper.writeValueAsString(map);String pStr4 = objectMapper.writeValueAsString(users);LOGGER.info("bean=》json:{}",pStr1);LOGGER.info("list=》json:{}",pStr2);LOGGER.info("map=》json:{}",pStr3);LOGGER.info("beans=》jsons:{}",pStr4);//json字符串转java对象:String json = "{\"id\":0,\"username\":\"张三\",\"email\":\"123@qq.com\",\"password\":\"123\",\"phoneNum\":\"456\"}";User bean = new ObjectMapper().readValue(json, User.class);LOGGER.info("json =》bean:{},username ={}",bean,bean.getUsername());//json字符串转list对象:TypeReference匿名内部类,指明对象类型String json2 = "[\"苹果\",\"橘子\"]";List<String> beanList = new ObjectMapper().readValue(json2, new TypeReference<List<String>>() {});LOGGER.info("list =》bean:{}",beanList);//json字符串转map对象:String json3 ="{\"name\":\"张三\",\"age\":20}";Map<String,Object> beanMap = new ObjectMapper().readValue(json3, new TypeReference<HashMap<String,Object>>(){});LOGGER.info("map =》bean:{}",beanMap);//JSON数组字符串->对象数组String json4 = "[{\"id\":0,\"username\":\"张三\",\"email\":\"123@qq.com\",\"password\":\"123\",\"phoneNum\":\"456\"},{\"id\":2,\"username\":\"李四\",\"email\":\"邮箱\",\"password\":\"密码\",\"phoneNum\":\"电话\"}]";User[] cars2 = objectMapper.readValue(json4, User[].class);LOGGER.info("jsons =》beans:{}",beanMap);}
}
打印如下
2023-05-30 01:03:54.842 INFO 14444 --- [ main] ngbootalinbabaSsmStart01ApplicationTests : bean=》json:{"id":0,"username":"张三","email":"123@qq.com","password":"123","phoneNum":"456"}
2023-05-30 01:03:54.842 INFO 14444 --- [ main] ngbootalinbabaSsmStart01ApplicationTests : list=》json:["苹果","橘子"]
2023-05-30 01:03:54.842 INFO 14444 --- [ main] ngbootalinbabaSsmStart01ApplicationTests : map=》json:{"name":"张三","age":20}
2023-05-30 01:03:54.842 INFO 14444 --- [ main] ngbootalinbabaSsmStart01ApplicationTests : beans=》jsons:[{"id":0,"username":"张三","email":"123@qq.com","password":"123","phoneNum":"456"},{"id":2,"username":"李四","email":"邮箱","password":"密码","phoneNum":"电话"}]
2023-05-30 01:03:54.866 INFO 14444 --- [ main] ngbootalinbabaSsmStart01ApplicationTests : json =》bean:User(id=0, username=张三, email=123@qq.com, password=123, phoneNum=456),username =张三
2023-05-30 01:03:54.866 INFO 14444 --- [ main] ngbootalinbabaSsmStart01ApplicationTests : list =》bean:[苹果, 橘子]
2023-05-30 01:03:54.872 INFO 14444 --- [ main] ngbootalinbabaSsmStart01ApplicationTests : map =》bean:{name=张三, age=20}
2023-05-30 01:03:54.872 INFO 14444 --- [ main] ngbootalinbabaSsmStart01ApplicationTests : jsons =》beans:{name=张三, age=20}
Java对象转JSON相关注解
@JsonIgnore:排除属性。
@JsonFormat:属性值得格式化
- @JsonFormat(pattern = “yyyy-MM-dd”)
Person类
package com.demo.entity;import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {private Integer id;private String name;@JsonIgnoreprivate Integer age;@JsonIgnoreprivate String addr;@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date birthday;
}
测试方法
@Test
public void test3() throws Exception {Person person = new Person();person.setId(20);person.setName("Tom");person.setAge(23);person.setAddr("QD");person.setBirthday(new Date());ObjectMapper objectMapper = new ObjectMapper();String s = objectMapper.writeValueAsString(person);System.out.println(s); // {"id":20,"name":"Tom","birthday":"2023-05-29 17:07:35"}
}
Fastjson使用(Alibaba)
Maven构件地址 | Github地址
目前最新版本为 1.2.76 jar包大小为 533kb
阿里出品的json库,解析速度非常快。但是被曝出过漏洞问题,使用最新版的就好。
快速入门
引入依赖
pom.xml
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version>
</dependency>
代码测试
package com.demo;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.entity.User;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@SpringBootTest
class Test02 {private static final Logger LOGGER = LoggerFactory.getLogger(Test02.class);@Testpublic void test6() {//创建对象User user = new User();user.setId(0L);user.setUsername("张三");user.setEmail("123@qq.com");user.setPassword("123");user.setPhoneNum("456");User[] users = {user,new User(2L,"李四","邮箱","密码","电话")};ArrayList<String> list = new ArrayList<>();list.add("苹果");list.add("橘子");HashMap<String, Object> map = new HashMap<>();map.put("name", "张三");map.put("age", 20);//java对象(包括list、map)转json字符串String pStr1 = JSON.toJSONString(user);String pStr2 = JSON.toJSONString(list);String pStr3 = JSON.toJSONString(map);String pStr4 = JSON.toJSONString(users);System.out.println("bean=》json:"+pStr1);System.out.println("list=》json:"+pStr2);System.out.println("map=》json:"+pStr3);System.out.println("beans=》jsons:"+pStr4);//json字符串转java对象:User bean= JSONObject.parseObject("{\"username\":\"张三\"}", User.class);System.out.println(bean);//json字符串转list对象:List<String> beanList =JSONObject.parseArray("[\"苹果\",\"橘子\"]", String.class);System.out.println(beanList);//json字符串转map对象:Map<String,Object> beanMap = ( Map<String,Object> )JSONObject.parse("{\"name\":\"张三\",\"age\":20}");System.out.println(beanMap);}}
bean=》json:{"email":"123@qq.com","id":0,"password":"123","phoneNum":"456","username":"张三"}
list=》json:["苹果","橘子"]
map=》json:{"name":"张三","age":20}
beans=》jsons:[{"email":"123@qq.com","id":0,"password":"123","phoneNum":"456","username":"张三"},{"email":"邮箱","id":2,"password":"密码","phoneNum":"电话","username":"李四"}]
User(id=null, username=张三, email=null, password=null, phoneNum=null)
[苹果, 橘子]
{"name":"张三","age":20}
2023-05-30 01:24:15.688 INFO 13616 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closing ...
2023-05-30 01:24:15.688 INFO 13616 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closed
Disconnected from the target VM, address: '127.0.0.1:14228', transport: 'socket'
Gson
功能最全的json解析器,google谷歌出品
Maven构件地址 | Github地址
目前最新版为 2.8.6 其jar大小为 235kb
快速入门
引入依赖
<dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.6</version></dependency>
代码测试
package com.demo;import com.demo.entity.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@SpringBootTest
class Test03 {private static final Logger LOGGER = LoggerFactory.getLogger(Test03.class);@Testpublic void test6() {//创建对象User user = new User();user.setId(0L);user.setUsername("张三");user.setEmail("123@qq.com");user.setPassword("123");user.setPhoneNum("456");User[] users = {user,new User(2L,"李四","邮箱","密码","电话")};ArrayList<String> list = new ArrayList<>();list.add("苹果");list.add("橘子");HashMap<String, Object> map = new HashMap<>();map.put("name", "张三");map.put("age", 20);//java对象(包括list、map)转json字符串String pStr1 = new Gson().toJson(user);String pStr2 = new Gson().toJson(list);String pStr3 = new Gson().toJson(map);String pStr4 = new Gson().toJson(users);System.out.println("bean=》json:"+pStr1);System.out.println("list=》json:"+pStr2);System.out.println("map=》json:"+pStr3);System.out.println("beans=》jsons:"+pStr4);//json字符串转java对象:User bean= new Gson().fromJson("{\"username\":\"张三\"}", User.class);System.out.println(bean);//json字符串转list对象:List<String> beanList =new Gson().fromJson("[\"苹果\",\"橘子\"]", new TypeToken<List<String>>(){}.getType());System.out.println(beanList);//json字符串转map对象:Map<String,Object> beanMap = new Gson().fromJson("{\"name\":\"张三\",\"age\":20}", new TypeToken<HashMap<String,Object>>(){}.getType());System.out.println(beanMap);}}
list=》json:["苹果","橘子"]
map=》json:{"name":"张三","age":20}
beans=》jsons:[{"id":0,"username":"张三","email":"123@qq.com","password":"123","phoneNum":"456"},{"id":2,"username":"李四","email":"邮箱","password":"密码","phoneNum":"电话"}]
User(id=null, username=张三, email=null, password=null, phoneNum=null)
[苹果, 橘子]
{name=张三, age=20.0}