使用spring boot开发时java对象和Json对象转换

简介: 使用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>

二、jackson转换

1.构建User实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserEntity {


    private String userName;

    private int age;

    private String sex;
    
}

代码如下(示例):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
import  ssl
ssl._create_default_https_context = ssl._create_unverified_context

2.controller类

Java对象转换为json对象

@Controller
public 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转换

  1. 引入上述gson依赖
  2. Controller类
@RestController
public 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;
    }
}

四、fastjson转换

  1. 引入相关依赖
  2. Controller类
@RestController
public 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;
    }
}
目录
相关文章
|
4天前
|
XML Java 测试技术
Spring5入门到实战------17、Spring5新功能 --Nullable注解和函数式注册对象。整合JUnit5单元测试框架
这篇文章介绍了Spring5框架的三个新特性:支持@Nullable注解以明确方法返回、参数和属性值可以为空;引入函数式风格的GenericApplicationContext进行对象注册和管理;以及如何整合JUnit5进行单元测试,同时讨论了JUnit4与JUnit5的整合方法,并提出了关于配置文件加载的疑问。
Spring5入门到实战------17、Spring5新功能 --Nullable注解和函数式注册对象。整合JUnit5单元测试框架
|
4天前
|
人工智能 自然语言处理 Java
Spring AI,Spring团队开发的新组件,Java工程师快来一起体验吧
文章介绍了Spring AI,这是Spring团队开发的新组件,旨在为Java开发者提供易于集成的人工智能API,包括机器学习、自然语言处理和图像识别等功能,并通过实际代码示例展示了如何快速集成和使用这些AI技术。
Spring AI,Spring团队开发的新组件,Java工程师快来一起体验吧
|
1天前
|
前端开发 IDE Java
"揭秘前端转Java的秘径:SpringBoot Web极速入门,掌握分层解耦艺术,让你的后端代码飞起来,你敢来挑战吗?"
【8月更文挑战第19天】面向前端开发者介绍Spring Boot后端开发,通过简化Spring应用搭建,快速实现Web应用。本文以创建“Hello World”应用为例,展示项目基本结构与运行方式。进而深入探讨三层架构(Controller、Service、DAO)下的分层解耦概念,通过员工信息管理示例,演示各层如何协作及依赖注入的使用,以此提升代码灵活性与可维护性。
|
4天前
|
XML 数据库 数据格式
Spring5入门到实战------14、完全注解开发形式 ----JdbcTemplate操作数据库(增删改查、批量增删改)。具体代码+讲解 【终结篇】
这篇文章是Spring5框架的实战教程的终结篇,介绍了如何使用注解而非XML配置文件来实现JdbcTemplate的数据库操作,包括增删改查和批量操作,通过创建配置类来注入数据库连接池和JdbcTemplate对象,并展示了完全注解开发形式的项目结构和代码实现。
Spring5入门到实战------14、完全注解开发形式 ----JdbcTemplate操作数据库(增删改查、批量增删改)。具体代码+讲解 【终结篇】
|
5天前
|
Java
Java SpringBoot 7z 压缩、解压
Java SpringBoot 7z 压缩、解压
16 1
|
5天前
|
Java API 开发者
JDK8到JDK17版本升级的新特性问题之SpringBoot选择JDK17作为最小支持的Java lts版本意味着什么
JDK8到JDK17版本升级的新特性问题之SpringBoot选择JDK17作为最小支持的Java lts版本意味着什么
JDK8到JDK17版本升级的新特性问题之SpringBoot选择JDK17作为最小支持的Java lts版本意味着什么
|
5天前
|
JSON 前端开发 JavaScript
JSON parse error: Cannot deserialize value of type `java.lang.Integer` from Boolean value
这篇文章讨论了前端Vue应用向后端Spring Boot服务传输数据时发生的类型不匹配问题,即后端期望接收的字段类型为`int`,而前端实际传输的类型为`Boolean`,导致无法反序列化的问题,并提供了问题的诊断和解决方案。
JSON parse error: Cannot deserialize value of type `java.lang.Integer` from Boolean value
|
4天前
|
XML Java 数据库
Spring5入门到实战------10、操作术语解释--Aspectj注解开发实例。AOP切面编程的实际应用
这篇文章是Spring5框架的实战教程,详细解释了AOP的关键术语,包括连接点、切入点、通知、切面,并展示了如何使用AspectJ注解来开发AOP实例,包括切入点表达式的编写、增强方法的配置、代理对象的创建和优先级设置,以及如何通过注解方式实现完全的AOP配置。
|
5天前
|
Java 知识图谱
知识图谱(Knowledge Graph)- Neo4j 5.10.0 使用 - Java SpringBoot 操作 Neo4j
知识图谱(Knowledge Graph)- Neo4j 5.10.0 使用 - Java SpringBoot 操作 Neo4j
12 0
|
5天前
|
Java 测试技术 Spring
Java SpringBoot 加载 yml 配置文件中字典项
Java SpringBoot 加载 yml 配置文件中字典项
10 0

热门文章

最新文章