使用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月前
|
JSON 网络协议 安全
【Java】(10)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
109 1
|
1月前
|
JSON 网络协议 安全
【Java基础】(1)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
116 1
|
4月前
|
JSON Java 数据格式
Spring Boot返回Json数据及数据封装
在Spring Boot中,接口间及前后端的数据传输通常使用JSON格式。通过@RestController注解,可轻松实现Controller返回JSON数据。该注解是Spring Boot新增的组合注解,结合了@Controller和@ResponseBody的功能,默认将返回值转换为JSON格式。Spring Boot底层默认采用Jackson作为JSON解析框架,并通过spring-boot-starter-json依赖集成了相关库,包括jackson-databind、jackson-datatype-jdk8等常用模块,简化了开发者对依赖的手动管理。
484 3
|
5月前
|
JSON IDE Java
鸿蒙开发:json转对象插件回来了
首先,我重新编译了插件,进行了上传,大家可以下载最新的安装包进行体验了,还是和以前一样,提供了在线版和IDE插件版,两个选择,最新的版本,除了升级了版本,兼容了最新的DevEco Studio ,还做了一层优化,就是针对嵌套对象和属性的生成,使用方式呢,一年前的文章中有过详细的概述,这里呢也简单介绍一下。
182 4
鸿蒙开发:json转对象插件回来了
|
8月前
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot中的全局异常处理——定义返回的统一 json 结构
本课主要讲解Spring Boot中的全局异常处理方法。在项目开发中,各层操作难免会遇到各种异常,若逐一处理将导致代码耦合度高、维护困难。因此,需将异常处理从业务逻辑中分离,实现统一管理与友好反馈。本文通过定义一个简化的JsonResult类(含状态码code和消息msg),结合全局异常拦截器,展示如何封装并返回标准化的JSON响应,从而提升代码质量和用户体验。
192 0
|
8月前
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——封装统一返回的数据结构
本文介绍了在Spring Boot中封装统一返回的数据结构的方法。通过定义一个泛型类`JsonResult&lt;T&gt;`,包含数据、状态码和提示信息三个属性,满足不同场景下的JSON返回需求。例如,无数据返回时可设置默认状态码&quot;0&quot;和消息&quot;操作成功!&quot;,有数据返回时也可自定义状态码和消息。同时,文章展示了如何在Controller中使用该结构,通过具体示例(如用户信息、列表和Map)说明其灵活性与便捷性。最后总结了Spring Boot中JSON数据返回的配置与实际项目中的应用技巧。
637 0
|
8月前
|
JSON Java fastjson
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——使用 fastJson 处理 null
本文介绍如何使用 fastJson 处理 null 值。与 Jackson 不同,fastJson 需要通过继承 `WebMvcConfigurationSupport` 类并覆盖 `configureMessageConverters` 方法来配置 null 值的处理方式。例如,可将 String 类型的 null 转为 &quot;&quot;,Number 类型的 null 转为 0,避免循环引用等。代码示例展示了具体实现步骤,包括引入相关依赖、设置序列化特性及解决中文乱码问题。
394 0
|
8月前
|
JSON Java fastjson
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——Spring Boot 默认对Json的处理
本文介绍了在Spring Boot中返回Json数据的方法及数据封装技巧。通过使用`@RestController`注解,可以轻松实现接口返回Json格式的数据,默认使用的Json解析框架是Jackson。文章详细讲解了如何处理不同数据类型(如类对象、List、Map)的Json转换,并提供了自定义配置以应对null值问题。此外,还对比了Jackson与阿里巴巴FastJson的特点,以及如何在项目中引入和配置FastJson,解决null值转换和中文乱码等问题。
1168 0
|
11月前
|
XML 安全 Java
Spring Boot中使用MapStruct进行对象映射
本文介绍如何在Spring Boot项目中使用MapStruct进行对象映射,探讨其性能高效、类型安全及易于集成等优势,并详细说明添加MapStruct依赖的步骤。
461 0
|
11月前
|
JSON Java 数据格式
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
231 25
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)