JSONObject如何轉為實體類對象
更新時間:2024年11月11日 09:17:31 作者:有點野的程序猿
介紹了JSONObject轉為實體類對象的三種方法:JSONObject中的toJavaObject方法和getObject方法支持深轉換,而JSON中的parseObject方法只能轉換一層對象,此外,還補充說明了在對JSON轉為實體類對象時,無論JSON中的數(shù)據(jù)字段是否多于或少于實體類中字段,轉化都不會報錯
JSONObject轉為實體類對象
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方法支持深轉換,可以轉換實體對象;
- 而JSON中的parseObject方法只能轉換一層對象;
深轉換
以上邊代碼中的js為例:
深轉換的的意思也就是如果在js中再put一個student對象,那么parseObject是不能轉換js中的student對象的。
補充說明
新增一個知識點
在對json轉為實體類對象時,無論json中的數(shù)據(jù)字段是否多于或少于實體類中字段,轉化都不會報錯
舉個例子:
//一個Student實體類,屬性包括姓名和年齡 @Data public class Student { private String name; private Integer age; }
寫一個轉為實體類的代碼
- 情況一: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); } }
結果
- 情況二: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); } }
結果
注:這個點其實挺重要的,這充分說明了一件事,那就是json數(shù)據(jù)格式的靈活性。
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringBoot啟動流程SpringApplication準備階段源碼分析
這篇文章主要為大家介紹了SpringBoot啟動流程SpringApplication準備階段源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04java提取字符串中數(shù)字string以及獲取字符串中的整數(shù)或小數(shù)
這篇文章主要給大家介紹了關于java提取字符串中數(shù)字string以及獲取字符串中的整數(shù)或小數(shù)的相關資料,需要的朋友可以參考下2023-08-08