Json 字串解析
阿新 • • 發佈:2021-01-12
json 字串解析
今天遇到一個請求json字串,格式如下
{"data":"{\"applyId\":\"123456\",\"status\":\"1\",\"result\":\"報備成功\"}","requestId":"123456","version":"1.0","timestamp":"2021-01-12 10:10:52.670"}
分析:
這個字串由data、其他欄位組成,其中data部分是帶轉義字元\的.
可見這個請求其實包含了兩個json串,一個是請求本身,一個是內部的data,所以對於內部的data要再進行一次解析轉換
{ "data":"{"applyId":"123456","status":"1","result":"報備成功"}","requestId":"123456", "version":"1.0", "timestamp":"2021-01-12 10:10:52.670" }
方法1:
public void notice(@RequestBody String request){ JSONObject json = JSONObject.parseObject(request); String dataStr = json.getString("data"); NoticeDO data = JSONObject.parseObject(dataStr,NoticeDO.class);
}
NoticeDo實體
public class NoticeDO { private String applyId; private String status; private String result; }
方法2:
public void notice(@RequestBody NoticeReq request){
// 對data進行解析 NoticeDO data = JSONObject.parseObject(request.getData(),NoticeDO.class);
}
NoticeReq 實體類
public class NoticeReq { private String requestId; private String version; private String timestamp; private String data;
}