java调用接口传JSON格式的String字符串,处理方式

接口参数样式:

{
  "enterpriseId": "613",
  "enterpriseName": "中旭学习平台A",
  "externalplanId": "75",
  "externalplanName": "《梦想合伙人》70万",
  "courseId": "164",
  "courseName": "《实效管理总裁班-财务罗盘》",
  "courseCode": "201905174066",
  "courseStartTime": "2019-05-21",
  "courseEndTime": "2019-05-23",
  "unit": "人",
  "quentity": "4",
  "userInfoList": [{
    "extranalId": "384",
    "userId": "59726",
    "userName": "就叫张三",
    "userMobile": "18010045368"
  }, {
    "extranalId": "385",
    "userId": "59727",
    "userName": "就叫李四",
    "userMobile": "18501981517"
  }]
}

java代码:


CourseSendOutStudentInfoEntity CourseSendOutStudentEntity = externalplanFlowService.queryCourseSendOut(enterpriseEntity.getId(),basicId,peroidId);
List courseStudentEntityList = externalplanFlowService.queryCourseStudentInfo(enterpriseEntity.getId(),basicId,peroidId);
    if(courseStudentEntityList != null && courseStudentEntityList.size()>0){
        CourseSendOutStudentEntity.setUserInfoList(courseStudentEntityList);
        Object obj = JSONArray.toJSON(CourseSendOutStudentEntity);
        PlanEntity plan = signupApiTask(obj.toString());
        if(!"1".equals(plan.getStatus())){
            result.setSuccess(false);
            result.setMsg("添加人员成功,数据传输机构失败!");
        }
    }else{
        Object obj = JSONArray.toJSON(CourseSendOutStudentEntity);
        String jsonstr = obj.toString();
        PlanEntity plan = signupApiTask(jsonstr);
        if(!"1".equals(plan.getStatus())){
            result.setSuccess(false);
            result.setMsg("添加人员成功,数据传输机构失败!");
        }
    }

接口调用方法: 

public PlanEntity signupApiTask(String json) {
        String url = "http://app.zxqg.com:7879/api/kttx/signup";//测试
        String result = HttpClientUtil.doPostJson(url, json);
        String unescapeJsonStr = StringEscapeUtils.unescapeJson(result);
        unescapeJsonStr = unescapeJsonStr.substring(1, unescapeJsonStr.length()-1);

        JSONObject jsonObject = JSONObject.parseObject(unescapeJsonStr);
        PlanEntity planEntity = jsonObject.toJavaObject(PlanEntity.class);
        return planEntity;
    }

 注意:

Object obj = JSONArray.toJSON(CourseSendOutStudentEntity);

这里当 CourseSendOutStudentEntity 里有为 null 的数据时, 在转json 时会丢失该 key 的问题

解决方法:

json = JSONArray.toJSON(CourseSendOutStudentEntity)
JSONObject.toJSONString(json,SerializerFeature.WriteMapNullValue)

不会丢失该 key ,会显示 null 

 

你可能感兴趣的:(开发随笔)