Json 字符串解析

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;
}

 

posted @ 2021-01-12 14:12  ysloong  阅读(319)  评论(0编辑  收藏  举报