前后端通过Json传数据,并将Json转化成实体类

今天尝试着用thymeleaf写马上就要使用的计算机基础知识大赛的比赛系统,然后卡在如何将多个对象通过form表单发送给后端,最后没有找到比较好的办法,只能使用js将需要发送的数据转化成Json然后使用ajax发送请求。然后在后台在将数据转化成实体类

首先我们的实体类如下:
package com.njupt.sacc.cbkc.problem.entity;

public class ProblemResult {

    private Integer id;
    private Integer uid;
    private Integer pid;
    private String result;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    @Override
    public String toString() {
        return "ProblemResult{" +
                "id=" + id +
                ", uid=" + uid +
                ", pid=" + pid +
                ", result='" + result + '\'' +
                '}';
    }
}
然后我们的目标就是前端向后端发送多个ProblemResult对象,然后在进行处理,首先我们看前端的实现方案(此时后端向前端发送的是一个List):
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

</head>
<body>
<hr>
<div th:each="problem : ${problems}">
    <span th:text="${problem.id}"></span>
    <form th:object="${problem}" th:if="${problem.isSingle == 1}">
        <input type="radio" th:name="${problem.id}" th:text="${problem.aOption}" value="a">
        <input type="radio" th:name="${problem.id}" th:text="${problem.bOption}" value="b">
        <input type="radio" th:name="${problem.id}" th:text="${problem.cOption}" value="c">
        <input type="radio" th:name="${problem.id}" th:text="${problem.dOption}" value="d">
    </form>
    <form th:object="${problem}" th:if="${problem.isSingle == 0}">
        <input type="checkbox" th:name="${problem.id}" th:text="${problem.aOption}" value="a">
        <input type="checkbox" th:name="${problem.id}" th:text="${problem.bOption}" value="b">
        <input type="checkbox" th:name="${problem.id}" th:text="${problem.cOption}" value="c">
        <input type="checkbox" th:name="${problem.id}" th:text="${problem.dOption}" value="d">
    </form>
    <hr>
</div>
<button name="save" onclick="loadXMLDoc(name)">保存</button>
<button name="push" onclick="loadXMLDoc(name)">提交</button>

<script type="text/javascript">
    //将答案转化成Json格式
    //name用来判断是保存操作还是提交操作
    function f(name) {
        var json = [];
        //[[$[count]]]为thymeleaf中js获取值的方法
        var count = [[${count}]];
        for (var i = 1; i <= count; i++) {
            var type = document.getElementsByName(i).item(0).getAttribute("type");
            //js获取单选框的值
            if (type == "radio") {
                var radio = document.getElementsByName(i);
                var result = "";
                for (var j = 0; j < radio.length; j++) {
                    if (radio[j].checked) {
                        result = radio[j].value;
                        break;
                    }
                }
            } else {//js获取多选框的值
                var checkbox = document.getElementsByName(i);
                var result = "";
                for (var j = 0; j < checkbox.length; j++) {
                    if (checkbox[j].checked)
                        result = result + checkbox[j].value;
                }
            }
            var row = {"pid": i, "result": result};
            json.push(row);
        }
        return {"type":name,"data":json};
    }
    //发送ajax请求
    function loadXMLDoc(name) {
        var xmlhttp;
        if (window.XMLHttpRequest) {
            //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
            xmlhttp = new XMLHttpRequest();
        } else {
            // IE6, IE5 浏览器执行代码
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                console.log("successful");
            }
        };
        xmlhttp.open("POST", "/test", true);
        xmlhttp.setRequestHeader("Content-Type", "application/json");
        var data = f(name);
        xmlhttp.send(JSON.stringify(data));
    }
</script>
</body>
</html>
传送的数据示例大致如下:
{
	"submit":[
		{"pid":1,"result":"a"},
		{"pid":2,"result":"ab"},
		{"pid":3,"result":""},
		{"pid":4,"result":"abcd"},
		{"pid":5,"result":"a"},
		{"pid":6,"result":"d"},
		{"pid":7,"result":"b"},
		{"pid":8,"result":"c"}
	],
	"type":"save"
}
之后我们看后端如何获取数据并将数据转化成实体类:
@RequestMapping("/test")
    public String submit(@RequestBody JSONObject jsonObject){
        //通过key获取前端发送的json的数组
        JSONArray problemResults = jsonObject.getJSONArray("data");
        //通过key获取前端发送的json中的type字段
        String submitType = String.valueOf(jsonObject.get("type"));
        List<ProblemResult> list = new ArrayList<>();
        //通过遍历将json数据中的数据转化成实体类
        for (Object problemResult : problemResults) {
            //会用JSONObject包中的函数将字符串转化成实体类
            ProblemResult result = (ProblemResult) JSONObject.toJavaObject((JSONObject) problemResult, ProblemResult.class);
            list.add(result);
        }
        return "index";
    }

经过上面的操作,我们就成功的完成了前端向后端发送多个对象,整体思想大概就是先把需要传的所有对象看成一个数组,然后传到后端之后再对json数据进行解析,然后获取数据中的json字符串,然后通过json库中的函数将json字符串转化成实体类,全部完成

参考博文:

阿里巴巴的JSONObject对象转换 https://blog.csdn.net/a990914093/article/details/81217581
JSONObject如何转换成实体类型
https://blog.csdn.net/m0_38129335/article/details/80047034
json数据与实体类之间的相互转换
https://blog.csdn.net/nandao158/article/details/71122851

你可能感兴趣的:(SpringBoot,Java)