當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JSON与对象之间的相互转换
生活随笔
收集整理的這篇文章主要介紹了
JSON与对象之间的相互转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 創建實體類對象
@Data public class ResponseInfo {/*** 工單ID*/private String orderId;/***接收結果* 1:成功* 2:失敗*/enum result{成功("1"),失敗("2");private String value;private result(String value){this.value = value;}public String getValue(){return this.value;}}/*** 錯誤信息*/private String errorMsg;}給對象賦值,并轉為JSON(對象轉JSON)
ResponseInfo responseInfo = new ResponseInfo();responseInfo.setOrderId("2222222");responseInfo.setErrorMsg("你錯了,錯誤在這里");String result = JSONObject.toJSONString(responseInfo);System.out.println("=========="+result);輸出結果為:
將JSON轉為對象(JSON轉為對象)
準備一個接收的對象,需要注意的是:接收對象內的字段與JSON字符串里面的字段需要一一對應,可以有多余的字段,如下:
@Data public class ResponseInfoDto {/*** 工單ID*/private String orderId;/***接收結果* 1:成功* 2:失敗*/enum result{成功("1"),失敗("2");private String value;private result(String value){this.value = value;}public String getValue(){return this.value;}}/*** 錯誤信息*/private String errorMsg;private String msg;}實現JSONObject.parseObject(JSON字符串,接收對象.class);
ResponseInfoDto response = JSONObject.parseObject(result,ResponseInfoDto.class); System.out.println("************"+response);輸出結果
總結
以上是生活随笔為你收集整理的JSON与对象之间的相互转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 跳出内层循环 使用 for of 代替
- 下一篇: Spring Boot 入门之缓存和 N