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

 更新时间:2021年03月02日 11:17:48   作者:BBQ__XB  
这篇文章主要介绍了使用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转换

引入上述gson依赖

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转换

引入相关依赖

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;
  }
}

到此这篇关于使用spring boot开发时java对象和Json对象转换的问题的文章就介绍到这了,更多相关spring boot java对象和Json对象转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java编程中的vector类用法学习笔记

    Java编程中的vector类用法学习笔记

    Vector通常被用来实现动态数组,即可实现自动增长的对象数组,和C++一样vector类同样被Java内置,下面就来看一下vector类的基本用法.
    2016-05-05
  • 详解springMVC—三种控制器controller

    详解springMVC—三种控制器controller

    本篇文章主要介绍了springMVC—三种控制器controller,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-03-03
  • Java类如何实现一个类的障眼法(JadClipse的bug)

    Java类如何实现一个类的障眼法(JadClipse的bug)

    这篇文章主要介绍了Java类实现一个类的障眼法(JadClipse的bug),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • MyBatis 动态SQL和缓存机制实例详解

    MyBatis 动态SQL和缓存机制实例详解

    这篇文章主要介绍了MyBatis 动态SQL和缓存机制实例详解,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2017-09-09
  • Spring详细讲解事务失效的场景

    Spring详细讲解事务失效的场景

    实际项目开发中,如果涉及到多张表操作时,为了保证业务数据的一致性,大家一般都会采用事务机制,好多小伙伴可能只是简单了解一下,遇到事务失效的情况,便会无从下手,下面这篇文章主要给大家介绍了关于Spring事务失效场景的相关资料,需要的朋友可以参考下
    2022-07-07
  • 使用@CacheEvict清除指定下所有缓存

    使用@CacheEvict清除指定下所有缓存

    这篇文章主要介绍了使用@CacheEvict清除指定下所有缓存,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • mybatis查询oracle long类型的踩坑记录

    mybatis查询oracle long类型的踩坑记录

    这篇文章主要介绍了mybatis查询oracle long类型的踩坑记录,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • Java中ArrayList和LinkedList有什么区别举例详解

    Java中ArrayList和LinkedList有什么区别举例详解

    这篇文章主要介绍了Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影响、扩容机制、线程安全与并发方案,以及工程实践场景,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2025-02-02
  • 关于@JsonProperty,@NotNull,@JsonIgnore的具体使用

    关于@JsonProperty,@NotNull,@JsonIgnore的具体使用

    这篇文章主要介绍了关于@JsonProperty,@NotNull,@JsonIgnore的具体使用,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-08-08
  • Java中id,pid格式数据转树和森林结构工具类实现

    Java中id,pid格式数据转树和森林结构工具类实现

    本文主要介绍了Java中id,pid格式数据转树和森林结构工具类实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-05-05

最新评论