欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Jackson中json格式的字符串與對象的互相轉(zhuǎn)換方式

 更新時(shí)間:2022年07月05日 14:21:24   作者:hestyle  
這篇文章主要介紹了Jackson中json格式的字符串與對象的互相轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

json格式的字符串與對象的互相轉(zhuǎn)換

Jackson 簡介

Jackson是一個(gè)簡單基于Java應(yīng)用庫,Jackson可以輕松的將Java對象轉(zhuǎn)換成json字符串和xml文檔,同樣也可以將json、xml轉(zhuǎn)換成Java對象。Jackson所依賴的jar包較少,簡單易用并且性能也要相對高些,并且Jackson社區(qū)相對比較活躍,更新速度也比較快。

jackson特點(diǎn)

  • 容易使用 - jackson API提供了一個(gè)高層次外觀,以簡化常用的用例。
  • 無需創(chuàng)建映射 - API提供了默認(rèn)的映射大部分對象序列化。
  • 性能高 - 快速,低內(nèi)存占用,適合大型對象圖表或系統(tǒng)。
  • 干凈的JSON - jackson創(chuàng)建一個(gè)干凈和緊湊的JSON結(jié)果,這是讓人很容易閱讀。
  • 不依賴 - 庫不需要任何其他的庫,除了JDK。
  • 開源代碼 - jackson是開源的,可以免費(fèi)使用。

json格式的字符串與對象的轉(zhuǎn)換

使用Jackson必須要在項(xiàng)目導(dǎo)入對應(yīng)的jar包。

Book.java文件

package cn.hestyle.bean;
public class Book {
	private String id;
	private String name;
	private double price;
	private int pnum;
	private String category;
	private String description;
	
	public Book() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Book(String id, String name, double price, int pnum, String category, String description) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.pnum = pnum;
		this.category = category;
		this.description = description;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public int getPnum() {
		return pnum;
	}
	public void setPnum(int pnum) {
		this.pnum = pnum;
	}
	public String getCategory() {
		return category;
	}
	public void setCategory(String category) {
		this.category = category;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", price=" + price + ", pnum=" + pnum + ", category=" + category
				+ ", description=" + description + "]";
	}
}
package cn.hestyle.utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import cn.hestyle.bean.Book;
public class JacksonDemo01 {
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		//將對象轉(zhuǎn)換為json格式的字符串
		Book book = new Book("1001", "Java入門到入土", 99.9, 100, "編程開發(fā)", "你懂得!");
		String bookJsonStr = objectMapper.writeValueAsString(book);
		System.out.println(bookJsonStr);
		//將集合、數(shù)組對象轉(zhuǎn)換為json格式的字符串
		List<Book> bookList = new ArrayList<Book>();
		bookList.add(new Book("1001", "Java入門到入土", 99.9, 100, "編程開發(fā)", "你懂得!"));
		bookList.add(new Book("1002", "Python入門到入土", 89.9, 100, "編程開發(fā)", "你懂得!"));
		bookList.add(new Book("1003", "C++入門到入土", 89.9, 200, "編程開發(fā)", "你懂得!"));
		String bookListJsonStr = objectMapper.writeValueAsString(bookList);
		System.out.println(bookListJsonStr);
		
		//將json格式的字符串轉(zhuǎn)化為對象
		//字符串中含有雙引號,需要使用反斜杠轉(zhuǎn)義
		String bookString = "{\"id\":\"1001\",\"name\":\"Java入門到入土\",\"price\":99.9,\"pnum\":100}";
		//Book必須有無參的構(gòu)造方法
		Book book2 = objectMapper.readValue(bookString, Book.class);
		System.out.println(book2);
	}
}

控制臺輸出:

Jackson進(jìn)行json轉(zhuǎn)對象,對象轉(zhuǎn)json總結(jié)

在前后端分離的項(xiàng)目中,后端經(jīng)常涉及到j(luò)son與對象互轉(zhuǎn)的場景。阿里巴巴的Fastjson是好用,但是,因?yàn)榧夹g(shù)領(lǐng)導(dǎo)的原因(可能因?yàn)閒astjson1的各種問題很多吧),不讓用,所以就需要選擇其他技術(shù)棧。當(dāng)前比較常用的是SpringBoot自帶的Jackson或者谷歌的Gson。

下面,做一下使用Jackson的總結(jié)。

JavaBean準(zhǔn)備

1.Company,公司

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Company {
    private String companyName;
    private List<WebSite> webSites;
}

2.WebSite,站點(diǎn)

@Data
@NoArgsConstructor
@AllArgsConstructor
public class WebSite {
    private String webSiteName;
    private List<User> users;
}

3.User,用戶

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String userId;
    private String username;
    private String password;
}

json字符串和對象互轉(zhuǎn)

對象轉(zhuǎn)json字符串

不管你是什么結(jié)構(gòu)的對象,想轉(zhuǎn)json,直接objectMapper.writeValueAsString()搞定。

    /**
     * 序列化:對象轉(zhuǎn)json字符串,包含多個(gè)數(shù)組
     *
     */
    @Test
    public void testObject2Json2() {
        User user2 = new User("1","上海辟謠專屬隊(duì)","職業(yè)辟謠,不信謠,不傳謠,呵呵");
        List<User> users = new ArrayList<>();
        users.add(user2);
        WebSite webSite = new WebSite();
        webSite.setWebSiteName("xxxxxx.com");
        webSite.setUsers(users);
        List<WebSite> webSites = new ArrayList<>();
        webSites.add(webSite);
        Company company = new Company();
        company.setCompanyName("yyyyyy");
        company.setWebSites(webSites);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonString = objectMapper.writeValueAsString(company);
            System.out.println(jsonString);
        } catch (JsonProcessingException e) {
            log.error("error: ", e);
        }
    }

輸出:

{"companyName":"yyyyyy","webSites":[{"webSiteName":"xxxxxx.com","users":[{"userId":"1","username":"上海辟謠專屬隊(duì)","password":"職業(yè)辟謠,不信謠,不傳謠,呵呵"}]}]}

json字符串轉(zhuǎn)對象

注意:這種情形是json對象字符串,不能是json數(shù)組字符串,后面會(huì)說到。

    @Test
    public void testJson2Object() {
        String json = "{\"companyName\":\"yyyyyy\",\"webSites\":[" +
                "{\"webSiteName\":\"xxxxxx.com\",\"users\":[{\"userId\":\"1\",\"username\":\"上海辟謠專屬隊(duì)\",\"password\":\"職業(yè)辟謠,不信謠,不傳謠,呵呵\"}]}" +
                "]}";
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Company company = objectMapper.readValue(json, Company.class);
            System.out.println(company.getWebSites().get(0).getUsers().get(0).getUsername());
        } catch (JsonProcessingException e) {
            log.error("error: ", e);
        }
    }

輸出:

上海辟謠專屬隊(duì)

json數(shù)組字符串和數(shù)組(集合)對象互轉(zhuǎn)

有個(gè)大坑

數(shù)組對象轉(zhuǎn)json數(shù)組字符串

    /**
     * 序列化:數(shù)組對象轉(zhuǎn)json數(shù)組類型的字符串
     *
     */
    @Test
    public void testObjectArray2JsonArrayString() {
        User user1 = new User("1","上海帶刀滬衛(wèi)","帶刀大佬");
        User user2 = new User("1","上海辟謠專屬隊(duì)","職業(yè)辟謠,不信謠,不傳謠,呵呵");
        List<User> users = new ArrayList<>();
        users.add(user1);
        users.add(user2);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String json = objectMapper.writeValueAsString(users);
            System.out.println(json);
        } catch (JsonProcessingException e) {
            log.error("error: ", e);
        }
    }

輸出:

[{"userId":"1","username":"上海帶刀滬衛(wèi)","password":"帶刀大佬"},{"userId":"1","username":"上海辟謠專屬隊(duì)","password":"職業(yè)辟謠,不信謠,不傳謠,呵呵"}]

json數(shù)組字符串轉(zhuǎn)數(shù)組對象

先演示一下錯(cuò)誤的寫法先演示一下錯(cuò)誤的寫法,先演示一下錯(cuò)誤的寫法,重要的事情說三遍!

    /**
     * 反序列化:數(shù)組類型的json字符串轉(zhuǎn)對象數(shù)組
     *
     */
    @Test
    public void testJsonArrayString2ObjectArray() {
        String json = "[" +
                "{\"userId\":\"1\",\"username\":\"上海帶刀滬衛(wèi)\",\"password\":\"帶刀大佬\(zhòng)"}" +
                ",{\"userId\":\"1\",\"username\":\"上海辟謠專屬隊(duì)\",\"password\":\"職業(yè)辟謠,不信謠,不傳謠,呵呵\"}" +
                "]";
        ObjectMapper objectMapper = new ObjectMapper();
        try {
			//錯(cuò)誤寫法
            List<User> list = objectMapper.readValue(json, List.class);
            list.forEach(user -> {
                System.out.println(user.getUsername());
            });
        } catch (JsonProcessingException e) {
            log.error("error: ", e);
        }
    }

輸出異常


java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.xywei.springboot.springtestdemo.entity.User

    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at com.xywei.springboot.springtestdemo.junit.TestUseJackson.testJsonArrayString2ObjectArray(TestUseJackson.java:160)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at 

#省略大段……
Process finished with exit code -1

因?yàn)閷?shí)際轉(zhuǎn)成了map類型,所以使用List方式取值是錯(cuò)的!

正確做法:

    /**
     * 反序列化:數(shù)組類型的json字符串轉(zhuǎn)對象數(shù)組
     *
     */
    @Test
    public void testJsonArrayString2ObjectArray() {
        String json = "[" +
                "{\"userId\":\"1\",\"username\":\"上海帶刀滬衛(wèi)\",\"password\":\"帶刀大佬\(zhòng)"}" +
                ",{\"userId\":\"1\",\"username\":\"上海辟謠專屬隊(duì)\",\"password\":\"職業(yè)辟謠,不信謠,不傳謠,呵呵\"}" +
                "]";
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            TypeReference<List<User>> typeReference = new TypeReference<List<User>>() {
            };
            List<User> list = objectMapper.readValue(json, typeReference);
            list.forEach(user -> {
                System.out.println(user.getUsername());
            });
        } catch (JsonProcessingException e) {
            log.error("error: ", e);
        }
    }

最終輸出:

上海帶刀滬衛(wèi)

上海辟謠專屬隊(duì)

同時(shí),對多層嵌套的數(shù)組也適用:

    @Test
    public void testJsonArrayString2ObjectArray2() {
        String json = "[" +
                    "{" +
                    "\"companyName\":\"yyyyyy\",\"webSites\":[" +
                            "{\"webSiteName\":\"xxxxxx.com\",\"users\":[" +
                                "{\"userId\":\"1\",\"username\":\"上海辟謠專屬隊(duì)\",\"password\":\"職業(yè)辟謠,不信謠,不傳謠,呵呵\"}" +
                                "]" +
                            "}" +
                        "]" +
                    "}" +
                "]";
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            TypeReference<List<Company>> typeReference = new TypeReference<List<Company>>() {
            };
            List<Company> list = objectMapper.readValue(json, typeReference);
            list.forEach(company -> {
                System.out.println(company.getWebSites().get(0).getUsers().get(0).getUsername());
            });
        } catch (JsonProcessingException e) {
            log.error("error: ", e);
        }
    }

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 解決IDEA報(bào)錯(cuò),無效的源發(fā)行版 無效的目標(biāo)發(fā)行版:22問題

    解決IDEA報(bào)錯(cuò),無效的源發(fā)行版 無效的目標(biāo)發(fā)行版:22問題

    在項(xiàng)目編譯過程中,可能會(huì)出現(xiàn)“無效的源發(fā)行版”或“無效的目標(biāo)發(fā)行版”的報(bào)錯(cuò)信息,原因通常是編譯使用的JDK版本與項(xiàng)目設(shè)置的發(fā)布版本不一致,解決這類問題的辦法是統(tǒng)一JDK版本,具體操作為:在IDE的項(xiàng)目設(shè)置中(如File->ProjectStructure->ProjectSettings)
    2024-10-10
  • Java中加鎖的方式代碼示例

    Java中加鎖的方式代碼示例

    這篇文章主要給大家介紹了關(guān)于Java中加鎖方式的相關(guān)資料,我們平時(shí)開發(fā)的過程中難免遇到多線程操作共享資源的時(shí)候,這時(shí)候一般可以通過加鎖的方式保證操作的安全性,需要的朋友可以參考下
    2023-09-09
  • SpringBoot中application.yml基本配置解讀

    SpringBoot中application.yml基本配置解讀

    文章主要介紹了Spring Boot項(xiàng)目中`application.properties`和`application.yml`配置文件的使用方法和區(qū)別,包括優(yōu)先級、配置文件所在目錄、端口服務(wù)配置、數(shù)據(jù)庫配置、多profile配置以及靜態(tài)資源路徑的指定
    2024-12-12
  • Java httpClient介紹以及使用示例

    Java httpClient介紹以及使用示例

    這篇文章主要介紹了Java httpClient介紹以及使用示例,幫助大家更好的利用Java實(shí)現(xiàn)HTTP請求,感興趣的朋友可以了解下
    2020-10-10
  • 淺談spring中scope作用域

    淺談spring中scope作用域

    這篇文章主要介紹了淺談spring中scope作用域,具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2017-12-12
  • 如何解決springboot數(shù)據(jù)庫查詢時(shí)出現(xiàn)的時(shí)區(qū)差異問題

    如何解決springboot數(shù)據(jù)庫查詢時(shí)出現(xiàn)的時(shí)區(qū)差異問題

    這篇文章主要介紹了如何解決springboot數(shù)據(jù)庫查詢時(shí)出現(xiàn)的時(shí)區(qū)差異問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • java中的類URL與URLConnection使用介紹

    java中的類URL與URLConnection使用介紹

    這篇文章主要為大家介紹了java中的類URL與URLConnection使用介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-06-06
  • 重寫equals的同時(shí)為何要重寫hashCode?

    重寫equals的同時(shí)為何要重寫hashCode?

    這篇文章主要給大家介紹了關(guān)于重寫equals的同時(shí)為何要重寫hashCode的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • Java 利用DeferredResult實(shí)現(xiàn)http輪詢實(shí)時(shí)返回?cái)?shù)據(jù)接口

    Java 利用DeferredResult實(shí)現(xiàn)http輪詢實(shí)時(shí)返回?cái)?shù)據(jù)接口

    這篇文章主要介紹了Java 利用 DeferredResult 實(shí)現(xiàn) http 輪詢實(shí)時(shí)返回?cái)?shù)據(jù)接口,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下
    2021-03-03
  • SpringBoot日志信息以及Lombok的常用注解詳析

    SpringBoot日志信息以及Lombok的常用注解詳析

    日志在我們的日常開發(fā)當(dāng)中是必定會(huì)用到的,這篇文章主要給大家介紹了關(guān)于SpringBoot日志信息以及Lombok的常用注解的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-12-12

最新評論