java与json相互转化_Jackson_Gson_Fastjson

news/2025/1/15 21:05:36/

日志概述

在日常实践中通常会对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 各自大小为

  1. jackson-core 314Kb
  2. jackson-databind 1.3Mb
  3. 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}

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

相关文章

平板触控笔哪种好?主动式电容笔推荐

现在市面上的电容笔分为主动式和被动式电容笔&#xff0c;很多小伙伴都分不清主动式和被动式电容笔的区别。今天给大家介绍一下这两款电容笔的区别。给大家分享几款好用的平替电容笔。 一、主动式电容笔和被动式电容笔的区别&#xff1a; 1.主动式电容笔&#xff1a; 主动式电…

解决蓝牙耳机自动暂停播放音乐的问题

有时候蓝牙耳机会莫名的暂停和播放音乐&#xff0c;这是因为这个耳机有红外感应功能&#xff0c;当蓝牙耳机检测到你摘下耳机时就暂停音乐&#xff0c;但是如果这个功能做的不好&#xff0c;就会自动暂定和播报放音乐&#xff0c;解决办法&#xff1a; 打开音乐播放器或者手机…

Android 10 如何解决蓝牙耳机听音乐过程,插入再拔出有线耳机,音乐不从蓝牙耳机发出

问题点&#xff1a;蓝牙耳机听音乐过程&#xff0c;插入再拔出有线耳机&#xff0c;音乐不从蓝牙耳机发出 代码路径&#xff1a; packages/apps/Bluetooth/src/com/android/bluetooth/btservice/ActiveDeviceManager.java a/src/com/android/bluetooth/btservice/ActiveDevice…

[RK3399-Android9.0] ES8316或ES8336 播放音乐时切换耳机,当状态栏耳机图标消失时,播放的音乐声音会关闭再打开一下的解决办法

问题描述&#xff1a; ES8316或ES8336 播放音乐时切换耳机&#xff0c;当状态栏耳机图标消失时&#xff0c;播放的音乐声音会关闭再打开一下的解决办法如下&#xff1a; frameworks\base\services\core\java\com\android\server\audio\AudioService.java private int checkSen…

蓝牙耳机连接笔记本后,音乐会断断续续,卡顿。

由于蓝牙传输带宽限制&#xff0c;在声音的传输中会有少许延迟。这个问题是无法避免的&#xff0c;改善的方法就是换一个好一点的耳机。 但是在蓝牙耳机连接到笔记本后&#xff0c;听歌时声音会出现断断续续的现象&#xff0c;时不时顿一下&#xff0c;十分影响体验。 后来发现…

苹果用什么蓝牙耳机好?适合苹果的音乐蓝牙耳机推荐

苹果耳机的市场一直以来都是火爆市场的&#xff0c;但价格一直都十分的高&#xff0c;近期我了解了多个品牌的蓝牙耳机&#xff0c;每个人对于蓝牙耳机的使用需求不同&#xff0c;下面我来推荐几款适合苹果的蓝牙耳机吧&#xff01; 一、南卡Lite pro2蓝牙耳机 耳机类型&…

简约而不失雅致,Sanag蓝牙耳机J2,让纯净音乐伴你左右

如今&#xff0c;真无线蓝牙耳机非常普遍&#xff0c;选择性也非常多。对于经常出差的我来说&#xff0c;耳机在便携性和续航等方面成了我最为关注的指标。新年初始&#xff0c;一款Sanag蓝牙耳机J2映入我的眼帘&#xff0c;它最为吸引我的是它独特的抽拉式充电仓设计&#xff…

骑行听音乐用什么耳机?骑行耳机推荐

作为一名骑行爱好者&#xff0c;自然少不了准备一副耳机。在骑行过程中不仅能听音乐还能连接手机&#xff0c;听地图导航十分的方便。市面上的而运动耳机琳琅满目&#xff0c;对于热爱运动的人来说一副适合自己的运动耳机必然会提高运动体验&#xff0c;如何挑选一副适合自己的…