使用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;
    }
}
目录
相关文章
|
19天前
|
Java
Java快速入门之类、对象、方法
本文简要介绍了Java快速入门中的类、对象和方法。首先,解释了类和对象的概念,类是对象的抽象,对象是类的具体实例。接着,阐述了类的定义和组成,包括属性和行为,并展示了如何创建和使用对象。然后,讨论了成员变量与局部变量的区别,强调了封装的重要性,通过`private`关键字隐藏数据并提供`get/set`方法访问。最后,介绍了构造方法的定义和重载,以及标准类的制作规范,帮助初学者理解如何构建完整的Java类。
|
18天前
|
安全 Java
Object取值转java对象
通过本文的介绍,我们了解了几种将 `Object`类型转换为Java对象的方法,包括强制类型转换、使用 `instanceof`检查类型和泛型方法等。此外,还探讨了在集合、反射和序列化等常见场景中的应用。掌握这些方法和技巧,有助于编写更健壮和类型安全的Java代码。
30 17
|
19天前
|
前端开发 Java 程序员
菜鸟之路day02-04拼图小游戏开发一一JAVA基础综合项目
本项目基于黑马程序员教程,涵盖面向对象进阶、继承、多态等知识,历时约24小时完成。项目去除了登录和注册模块,专注于单机游戏体验。使用Git进行版本管理,代码托管于Gitee。项目包含窗体搭建、事件监听、图片加载与打乱、交互逻辑实现、菜单功能及美化界面等内容。通过此项目,巩固了Java基础并提升了实际开发能力。 仓库地址:[https://gitee.com/zhang-tenglan/puzzlegame.git](https://gitee.com/zhang-tenglan/puzzlegame.git)
38 6
|
22天前
|
Java 应用服务中间件 API
【潜意识Java】javaee中的SpringBoot在Java 开发中的应用与详细分析
本文介绍了 Spring Boot 的核心概念和使用场景,并通过一个实战项目演示了如何构建一个简单的 RESTful API。
37 5
|
22天前
|
前端开发 Java 数据库连接
【潜意识Java】深度解读JavaWeb开发在Java学习中的重要性
深度解读JavaWeb开发在Java学习中的重要性
26 4
|
22天前
|
SQL Java API
|
Java 应用服务中间件 Maven
传统maven项目和现在spring boot项目的区别
Spring Boot:传统 Web 项目与采用 Spring Boot 项目区别
533 0
传统maven项目和现在spring boot项目的区别
|
XML Java 数据库连接
创建springboot项目的基本流程——以宠物类别为例
创建springboot项目的基本流程——以宠物类别为例
165 0
创建springboot项目的基本流程——以宠物类别为例
|
存储 机器学习/深度学习 IDE
SpringBoot 项目与被开发快速迁移|学习笔记
快速学习 SpringBoot 项目与被开发快速迁移
SpringBoot 项目与被开发快速迁移|学习笔记
|
Java Spring
自定义SpringBoot项目的启动Banner
``Banner``是``SpringBoot``框架一个特色的部分,其设计的目的无非就是一个框架的标识,其中包含了版本号、框架名称等内容,既然``SpringBoot``为我们提供了这个模块,它肯定也是可以更换的这也是``Spring``开源框架的设计理念。