JSONObject如何轉(zhuǎn)為實體類對象
JSONObject轉(zhuǎn)為實體類對象
JSONObject js = new JSONObject(); js.put("name", "張三"); js.put("age", 18); Student student = JSON.toJavaObject(js, Student.class); Student student1 = JSON.parseObject(String.valueOf(js), Student.class);
注:
- JSON中的toJavaObject方法和JSONObject中的getObject方法支持深轉(zhuǎn)換,可以轉(zhuǎn)換實體對象;
- 而JSON中的parseObject方法只能轉(zhuǎn)換一層對象;
深轉(zhuǎn)換
以上邊代碼中的js為例:
深轉(zhuǎn)換的的意思也就是如果在js中再put一個student對象,那么parseObject是不能轉(zhuǎn)換js中的student對象的。
補充說明
新增一個知識點
在對json轉(zhuǎn)為實體類對象時,無論json中的數(shù)據(jù)字段是否多于或少于實體類中字段,轉(zhuǎn)化都不會報錯
舉個例子:
//一個Student實體類,屬性包括姓名和年齡 @Data public class Student { private String name; private Integer age; }
寫一個轉(zhuǎn)為實體類的代碼
- 情況一:json字段多于實體類字段
public class test { public static void main(String[] args) { JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "zhangsan"); jsonObject.put("age", 18); jsonObject.put("gender", "male"); Student student = JSON.parseObject(String.valueOf(jsonObject), Student.class); Student student1 = JSON.toJavaObject(jsonObject, Student.class); System.out.println(student); System.out.println(student1); } }
結(jié)果
- 情況二:json字段少于實體類字段
public class test { public static void main(String[] args) { JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "zhangsan"); //jsonObject.put("age", 18); //jsonObject.put("gender", "male"); Student student = JSON.parseObject(String.valueOf(jsonObject), Student.class); Student student1 = JSON.toJavaObject(jsonObject, Student.class); System.out.println(student); System.out.println(student1); } }
結(jié)果
注:這個點其實挺重要的,這充分說明了一件事,那就是json數(shù)據(jù)格式的靈活性。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
java實現(xiàn)獲取安卓設(shè)備里已安裝的軟件包
本文給大家介紹的是如何獲取設(shè)備中已經(jīng)安裝的應(yīng)用軟件包的代碼,其核心方法原理很簡單,我們通過Android中提供的PackageManager類,來獲取手機中安裝的應(yīng)用程序信息2015-10-10SpringBoot啟動流程SpringApplication準備階段源碼分析
這篇文章主要為大家介紹了SpringBoot啟動流程SpringApplication準備階段源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04java提取字符串中數(shù)字string以及獲取字符串中的整數(shù)或小數(shù)
這篇文章主要給大家介紹了關(guān)于java提取字符串中數(shù)字string以及獲取字符串中的整數(shù)或小數(shù)的相關(guān)資料,需要的朋友可以參考下2023-08-08關(guān)于ArrayList初始創(chuàng)建設(shè)定長度問題
在使用ArrayList時,初始化長度并不等同于直接設(shè)定數(shù)組大小,如通過構(gòu)造函數(shù)指定長度,僅僅是在內(nèi)部開辟了相應(yīng)的存儲空間,并不會改變ArrayList的實際元素個數(shù),即size屬性仍然為0,因此,嘗試直接訪問未實際添加元素的位置會引發(fā)異常2024-11-11Spring AOP常見使用場景、術(shù)語及設(shè)計模式應(yīng)用方式
AOP是一種編程思想,可以將橫切關(guān)注點從業(yè)務(wù)邏輯中分離出來,以便更好地管理和維護,它通過使用Aspect、JoinPoint、Advice等術(shù)語來實現(xiàn),代理、裝飾器和攔截器等設(shè)計模式在AOP中經(jīng)常被使用2024-12-12