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. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法2. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析3. 淺談python出錯時(shí)traceback的解讀4. 利用promise及參數(shù)解構(gòu)封裝ajax請求的方法5. Python importlib動態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼6. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解7. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無效問題8. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向9. 在Android中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解10. Nginx+php配置文件及原理解析
