Spring jackson原理及基本使用方法詳解
導(dǎo)入maven依賴
<!-- 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>
1、java對象轉(zhuǎn)json
@Testpublic void test01() throws JsonProcessingException { //創(chuàng)建User對象 User user=new User('admin','1111'); //將user轉(zhuǎn)為json格式 ObjectMapper objectMapper=new ObjectMapper(); String userString=objectMapper.writeValueAsString(user); System.out.println(userString);}
2、writeValue(參數(shù)1,obj)方法介紹
參數(shù)1
File:將obj對象轉(zhuǎn)換為json字符串,并保存到指定的文件中 writer:將obj對象轉(zhuǎn)換為json字符串,并將json數(shù)據(jù)填充到字符輸出流中 Outputstream:將obj對象轉(zhuǎn)換為json字符串,并將json數(shù)據(jù)填充到字節(jié)輸出流中3、注解介紹
@JsonIgnore:排除屬性,即當(dāng)前注解屬性不轉(zhuǎn)化json @JsonFormat:屬性值的格式化常用在日期屬性上,eg:@sonFormat(pattern = 'yyyy-MM-dd')
4、json轉(zhuǎn)java對象
@Testpublic void test02() throws JsonProcessingException { //創(chuàng)建json對象 String json='{'username':'admin','password':'1111'}'; //將json對象轉(zhuǎn)為java對象 ObjectMapper objectMapper=new ObjectMapper(); User user=objectMapper.readValue(json,User.class); System.out.println(user);}
5、集合轉(zhuǎn)json
@Testpublic void test03() throws JsonProcessingException { //創(chuàng)建User對象 User user=new User('admin','1111'); //存儲User對象 List<User> userList=new ArrayList<User>(); userList.add(user); userList.add(user); userList.add(user); //集合轉(zhuǎn)json ObjectMapper objectMapper=new ObjectMapper(); String listJson=objectMapper.writeValueAsString(userList); System.out.println(listJson);}
注:map集合的轉(zhuǎn)換和list是一樣的
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. vue實(shí)現(xiàn)web在線聊天功能2. JavaEE SpringMyBatis是什么? 它和Hibernate的區(qū)別及如何配置MyBatis3. JavaScript實(shí)現(xiàn)頁面動態(tài)驗(yàn)證碼的實(shí)現(xiàn)示例4. Springboot 全局日期格式化處理的實(shí)現(xiàn)5. Java使用Tesseract-Ocr識別數(shù)字6. 完美解決vue 中多個echarts圖表自適應(yīng)的問題7. Python使用urlretrieve實(shí)現(xiàn)直接遠(yuǎn)程下載圖片的示例代碼8. SpringBoot+TestNG單元測試的實(shí)現(xiàn)9. 在Chrome DevTools中調(diào)試JavaScript的實(shí)現(xiàn)10. 解決Android Studio 格式化 Format代碼快捷鍵問題
