最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用spring boot開發(fā)時java對象和Json對象轉(zhuǎn)換的問題

 更新時間:2021年03月02日 11:17:48   作者:BBQ__XB  
這篇文章主要介紹了使用spring boot開發(fā)時java對象和Json對象轉(zhuǎn)換的問題,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

將java對象轉(zhuǎn)換為json對象,市面上有很多第三方j(luò)ar包,如下:

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>

一、構(gòu)建測試項目

開發(fā)工具為:IDEA
后端技術(shù):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相關(guān)依賴,這是因為Spring boot的起步依賴spring-boot-starter-web 已經(jīng)為我們傳遞依賴了Jackson JSON庫。

在這里插入圖片描述

當(dāng)我們不用它,而采用其他第三方j(luò)ar包時,我們可以排除掉它的依賴,可以為我們的項目瘦身。

<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轉(zhuǎn)換

1.構(gòu)建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對象轉(zhuǎn)換為json對象

@Controller
public class JsonController {

  @GetMapping("/json1")
  //思考問題,正常返回它會走視圖解析器,而json需要返回的是一個字符串
  //市面上有很多的第三方j(luò)ar包可以實現(xiàn)這個功能,jackson,只需要一個簡單的注解就可以實現(xiàn)了
  //@ResponseBody,將服務(wù)器端返回的對象轉(zhuǎn)換為json對象響應(yīng)回去
  @ResponseBody
  public String json1() throws JsonProcessingException {
    //需要一個jackson的對象映射器,就是一個類,使用它可以將對象直接轉(zhuǎn)換成json字符串
    ObjectMapper mapper = new ObjectMapper();
    //創(chuàng)建對象
    UserEntity userEntity = new UserEntity("笨笨熊", 18, "男");
    System.out.println(userEntity);
    //將java對象轉(zhuǎn)換為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對象轉(zhuǎn)換為json對象

@GetMapping("/json3")
  @ResponseBody
  public String json3() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    //Date默認返回時間戳,所以需要關(guān)閉它的時間戳功能
    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默認返回時間戳,所以需要關(guān)閉它的時間戳功能
    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;
  }
}

優(yōu)化后:

@GetMapping("/json4")
  @ResponseBody
  public String json4() throws JsonProcessingException {
    Date date = new Date();
    return JsonUtils.getJson(date);

  }

三、gson轉(zhuǎn)換

引入上述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轉(zhuǎn)換

引入相關(guān)依賴

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

到此這篇關(guān)于使用spring boot開發(fā)時java對象和Json對象轉(zhuǎn)換的問題的文章就介紹到這了,更多相關(guān)spring boot java對象和Json對象轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java編程中的vector類用法學(xué)習(xí)筆記

    Java編程中的vector類用法學(xué)習(xí)筆記

    Vector通常被用來實現(xiàn)動態(tài)數(shù)組,即可實現(xiàn)自動增長的對象數(shù)組,和C++一樣vector類同樣被Java內(nèi)置,下面就來看一下vector類的基本用法.
    2016-05-05
  • 詳解springMVC—三種控制器controller

    詳解springMVC—三種控制器controller

    本篇文章主要介紹了springMVC—三種控制器controller,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-03-03
  • Java類如何實現(xiàn)一個類的障眼法(JadClipse的bug)

    Java類如何實現(xiàn)一個類的障眼法(JadClipse的bug)

    這篇文章主要介紹了Java類實現(xiàn)一個類的障眼法(JadClipse的bug),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • MyBatis 動態(tài)SQL和緩存機制實例詳解

    MyBatis 動態(tài)SQL和緩存機制實例詳解

    這篇文章主要介紹了MyBatis 動態(tài)SQL和緩存機制實例詳解,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2017-09-09
  • Spring詳細講解事務(wù)失效的場景

    Spring詳細講解事務(wù)失效的場景

    實際項目開發(fā)中,如果涉及到多張表操作時,為了保證業(yè)務(wù)數(shù)據(jù)的一致性,大家一般都會采用事務(wù)機制,好多小伙伴可能只是簡單了解一下,遇到事務(wù)失效的情況,便會無從下手,下面這篇文章主要給大家介紹了關(guān)于Spring事務(wù)失效場景的相關(guān)資料,需要的朋友可以參考下
    2022-07-07
  • 使用@CacheEvict清除指定下所有緩存

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

    這篇文章主要介紹了使用@CacheEvict清除指定下所有緩存,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • mybatis查詢oracle long類型的踩坑記錄

    mybatis查詢oracle long類型的踩坑記錄

    這篇文章主要介紹了mybatis查詢oracle long類型的踩坑記錄,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Java中ArrayList和LinkedList有什么區(qū)別舉例詳解

    Java中ArrayList和LinkedList有什么區(qū)別舉例詳解

    這篇文章主要介紹了Java中ArrayList和LinkedList區(qū)別的相關(guān)資料,包括數(shù)據(jù)結(jié)構(gòu)特性、核心操作性能、內(nèi)存與GC影響、擴容機制、線程安全與并發(fā)方案,以及工程實踐場景,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2025-02-02
  • 關(guān)于@JsonProperty,@NotNull,@JsonIgnore的具體使用

    關(guān)于@JsonProperty,@NotNull,@JsonIgnore的具體使用

    這篇文章主要介紹了關(guān)于@JsonProperty,@NotNull,@JsonIgnore的具體使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • Java中id,pid格式數(shù)據(jù)轉(zhuǎn)樹和森林結(jié)構(gòu)工具類實現(xiàn)

    Java中id,pid格式數(shù)據(jù)轉(zhuǎn)樹和森林結(jié)構(gòu)工具類實現(xiàn)

    本文主要介紹了Java中id,pid格式數(shù)據(jù)轉(zhuǎn)樹和森林結(jié)構(gòu)工具類實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05

最新評論

钦州市| 刚察县| 江达县| 开江县| 宜兰县| 确山县| 赤壁市| 白河县| 诸暨市| 黄浦区| 安康市| 临湘市| 页游| 奇台县| 罗山县| 广东省| 高密市| 盘锦市| 大理市| 二连浩特市| 涪陵区| 句容市| 上蔡县| 永兴县| 莱芜市| 荣成市| 锡林郭勒盟| 深圳市| 六安市| 东乌珠穆沁旗| 仪陇县| 桃江县| 广安市| 阳山县| 称多县| 宁化县| 孟州市| 登封市| 乐安县| 东乌| 大庆市|