小编给大家分享一下如何使用Spring Boot开发时java对象和JSON对象转换的问题,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!将java对象转换为jso
小编给大家分享一下如何使用Spring Boot开发时java对象和JSON对象转换的问题,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
将java对象转换为json对象,市面上有很多第三方jar包,如下:
jackson(最常用)
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --><dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.2</version></dependency>
gson
<!-- Https://mvnrepository.com/artifact/com.Google.code.gson/gson --><dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version></dependency>
fastjson
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --><dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version></dependency>
开发工具为:idea
后端技术:spring boot ,Maven
引入依赖
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>json</artifactId> <version>0.0.1-SNAPSHOT</version> <name>json</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-WEB</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build></project>
可以从上面看出,并未引入Jackson相关依赖,这是因为Spring boot的起步依赖spring-boot-starter-web 已经为我们传递依赖了Jackson JSON库。
当我们不用它,而采用其他第三方jar包时,我们可以排除掉它的依赖,可以为我们的项目瘦身。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <artifactId>jackson-core</artifactId> <groupId>com.fasterxml.jackson.core</groupId> </exclusion> </exclusions></dependency>
import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data@NoArgsConstructor@AllArgsConstructorpublic class UserEntity { private String userName; private int age; private String sex; }
代码如下(示例):
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport warningswarnings.filterwarnings('ignore')import sslssl._create_default_https_context = ssl._create_unverified_context
Java对象转换为json对象
@Controllerpublic class JsonController { @GetMapping("/json1") //思考问题,正常返回它会走视图解析器,而json需要返回的是一个字符串 //市面上有很多的第三方jar包可以实现这个功能,jackson,只需要一个简单的注解就可以实现了 //@ResponseBody,将服务器端返回的对象转换为json对象响应回去 @ResponseBody public String json1() throws JsonProcessingException { //需要一个jackson的对象映射器,就是一个类,使用它可以将对象直接转换成json字符串 ObjectMapper mapper = new ObjectMapper(); //创建对象 UserEntity userEntity = new UserEntity("笨笨熊", 18, "男"); System.out.println(userEntity); //将java对象转换为json字符串 String str = mapper.writeValueAsString(userEntity); System.out.println(str); //由于使用了@ResponseBody注解,这里会将str以json格式的字符串返回。 return str; } @GetMapping("/json2") @ResponseBody public String json2() throws JsonProcessingException { ArrayList<UserEntity> userEntities = new ArrayList<>(); UserEntity user1 = new UserEntity("笨笨熊", 18, "男"); UserEntity user2 = new UserEntity("笨笨熊", 18, "男"); UserEntity user3 = new UserEntity("笨笨熊", 18, "男"); userEntities.add(user1); userEntities.add(user2); userEntities.add(user3); return new ObjectMapper().writeValueAsString(userEntities); }}
Date对象转换为json对象
@GetMapping("/json3") @ResponseBody public String json3() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); //Date默认返回时间戳,所以需要关闭它的时间戳功能 mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); //时间格式化问题 自定义时间格式对象 SimpleDateFORMat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //让mapper指定时间日期格式为simpleDateFormat mapper.setDateFormat(simpleDateFormat); //写一个时间对象 Date date = new Date(); return mapper.writeValueAsString(date); }
提取工具类JsonUtils
public class JsonUtils { public static String getJson(Object object){ return getJson(object,"yyyy-MM-dd HH:mm:ss"); } public static String getJson(Object object,String dateFormat) { ObjectMapper mapper = new ObjectMapper(); //Date默认返回时间戳,所以需要关闭它的时间戳功能 mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); //时间格式化问题 自定义时间格式对象 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); //让mapper指定时间日期格式为simpleDateFormat mapper.setDateFormat(simpleDateFormat); try{ return mapper.writeValueAsString(object); }catch (JsonProcessingException e){ e.printStackTrace(); } return null; }}
优化后:
@GetMapping("/json4") @ResponseBody public String json4() throws JsonProcessingException { Date date = new Date(); return JsonUtils.getJson(date); }
引入上述gson依赖
Controller类
@RestControllerpublic class gsonController { @GetMapping("/gson1") public String json1() throws JsonProcessingException { ArrayList<UserEntity> userEntities = new ArrayList<>(); UserEntity user1 = new UserEntity("笨笨熊", 18, "男"); UserEntity user2 = new UserEntity("笨笨熊", 18, "男"); UserEntity user3 = new UserEntity("笨笨熊", 18, "男"); userEntities.add(user1); userEntities.add(user2); userEntities.add(user3); Gson gson = new Gson(); String str = gson.toJson(userEntities); return str; }}
引入相关依赖
Controller类
@RestControllerpublic class FastJsonController { @GetMapping("/fastjson1") public String json1() throws JsonProcessingException { ArrayList<UserEntity> userEntities = new ArrayList<>(); UserEntity user1 = new UserEntity("笨笨熊", 18, "男"); UserEntity user2 = new UserEntity("笨笨熊", 18, "男"); UserEntity user3 = new UserEntity("笨笨熊", 18, "男"); userEntities.add(user1); userEntities.add(user2); userEntities.add(user3); String str = JSON.toJSONString(userEntities); return str; }}
以上是“如何使用spring boot开发时java对象和Json对象转换的问题”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程网精选频道!
--结束END--
本文标题: 如何使用spring boot开发时java对象和Json对象转换的问题
本文链接: https://lsjlt.com/news/247816.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0