1. 程式人生 > >前臺如何將多個json物件傳入java後臺(轉)

前臺如何將多個json物件傳入java後臺(轉)

前臺json格式的資料如何傳入後臺

1. 將要傳入後臺的資料組裝成JSON格式的字串:

var jsonStr = [{'name':'jim' , 'age':20} , {'name':'king' , 'age':26},{'name':'jge' , 'age':30}]

2. 使用jQuery的ajax請求後臺

jQuery.ajax({

type: "post",

url: url,

dataType : 'json',

data : {'mydata':jsonStr},

success: function(data,textStatus){

alert("操作成功");

},

error: function(xhr,status,errMsg){

alert("操作失敗!");

}

});

3.後臺資料的接收與解析:

String jsonStr = ServletActionContext.getRequest().getParameter("mydata");

JSONArray jsonArray = JSONArray.fromObject(jsonStr);

for(int i=0;i<jsonArray.length(); i++){

JSONObject jsonJ = jsonArray.getJSONObject(i);

jsonJ.getInt("name");

jsonJ.getString("age");

}

4. 操作完成

如果不行請參考:

@ApiOperation(value = "新增做題記錄")
@PostMapping("postAnswerLog")
public JSONObject postAnswerLog(@ApiIgnore @RequestAttribute(required = false) Integer userId,
                                 @ApiParam("試卷")@RequestParam Integer examinationPaperId,
                                 @ApiParam("題庫")@RequestParam String outlines
                                 ) {
    int flage = studentWordListService.postAnswerLog(userId,examinationPaperId,outlines);
    JSONObject json = new JSONObject();
    if(flage>0){
        json.put("state",200);
        json.put("msg", "成功");
    }else{
        json.put("state",400);
        json.put("msg", "失敗");
    }
    return json;
}
//新增做題記錄
@Override
public int postAnswerLog(Integer userId, Integer examinationPaperId, String outlines) {
    userId = 1;
    EducationAnswerLog educationAnswerLog = new EducationAnswerLog();
    educationAnswerLog.setStudentUseId(userId);
    educationAnswerLog.setExaminationPaperId(examinationPaperId);
    JSONArray jsonArray = JSONArray.fromObject(outlines);
    for(int i=0;i<jsonArray.size(); i++){
        JSONObject jsonJ = jsonArray.getJSONObject(i);
        educationAnswerLog.setOutlineId(jsonJ.getInt("outlineId"));
        educationAnswerLog.setAnswerDetails(jsonJ.getString("answerDetails"));
        try {
            educationAnswerLogMapper.insert(educationAnswerLog);
        }catch (Exception e) {
            return 0;
        }
    }
    return 1;
}