使用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;
    }
}
目录
相关文章
|
1天前
|
设计模式 JavaScript Java
[设计模式Java实现附plantuml源码~行为型] 对象状态及其转换——状态模式
[设计模式Java实现附plantuml源码~行为型] 对象状态及其转换——状态模式
|
1天前
|
Java Nacos 开发者
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
|
1天前
|
Dubbo Java 应用服务中间件
Java从入门到精通:3.2.2分布式与并发编程——了解分布式系统的基本概念,学习使用Dubbo、Spring Cloud等分布式框架
Java从入门到精通:3.2.2分布式与并发编程——了解分布式系统的基本概念,学习使用Dubbo、Spring Cloud等分布式框架
|
3天前
|
Java
Java基础之对象的引用
Java基础之对象的引用
5 0
|
6天前
|
Java Spring 容器
SpringBoot 使用Quartz执行定时任务对象时无法注入Bean问题
SpringBoot 使用Quartz执行定时任务对象时无法注入Bean问题
10 1
|
7天前
|
Java
Java中如何克隆一个对象?
【4月更文挑战第13天】
15 0
|
9天前
|
负载均衡 Java 开发者
细解微服务架构实践:如何使用Spring Cloud进行Java微服务治理
【4月更文挑战第17天】Spring Cloud是Java微服务治理的首选框架,整合了Eureka(服务发现)、Ribbon(客户端负载均衡)、Hystrix(熔断器)、Zuul(API网关)和Config Server(配置中心)。通过Eureka实现服务注册与发现,Ribbon提供负载均衡,Hystrix实现熔断保护,Zuul作为API网关,Config Server集中管理配置。理解并运用Spring Cloud进行微服务治理是现代Java开发者的关键技能。
|
9天前
|
Java API 数据库
深入解析:使用JPA进行Java对象关系映射的实践与应用
【4月更文挑战第17天】Java Persistence API (JPA) 是Java EE中的ORM规范,简化数据库操作,让开发者以面向对象方式处理数据,提高效率和代码可读性。它定义了Java对象与数据库表的映射,通过@Entity等注解标记实体类,如User类映射到users表。JPA提供持久化上下文和EntityManager,管理对象生命周期,支持Criteria API和JPQL进行数据库查询。同时,JPA包含事务管理功能,保证数据一致性。使用JPA能降低开发复杂性,但需根据项目需求灵活应用,结合框架如Spring Data JPA,进一步提升开发便捷性。
|
10天前
|
安全 Java 数据安全/隐私保护
使用Spring Security进行Java身份验证与授权
【4月更文挑战第16天】Spring Security是Java应用的安全框架,提供认证和授权解决方案。通过添加相关依赖到`pom.xml`,然后配置`SecurityConfig`,如设置用户认证信息和URL访问规则,可以实现应用的安全保护。认证流程包括请求拦截、身份验证、响应生成和访问控制。授权则涉及访问决策管理器,如基于角色的投票。Spring Security为开发者构建安全应用提供了全面且灵活的工具,涵盖OAuth2、CSRF保护等功能。
|
11天前
|
Java 大数据 云计算
Spring框架:Java后台开发的核心
【4月更文挑战第15天】Spring框架在Java后台开发中占据核心位置,因其控制反转(IoC)、面向切面编程(AOP)、事务管理等特性提升效率和质量。Spring提供数据访问集成、RESTful Web服务和WebSocket支持。优势包括高效开发、灵活扩展、强大生态圈和广泛应用。应用于企业级应用、微服务架构及云计算大数据场景。掌握Spring对Java开发者至关重要。