我将一个数组放入一个发送到 java webservice 的对象中(请参阅 javascript.js -> sendDataToWebservice())。 Web 服务处理该数组(通过 gson)并将其作为字符串保存在 sql 数据库中(请参阅 webservice.java -> handleDataFunction())。当我想要接收数组时,数据未正确转换回数组(请参阅 javascript.js -> receiveDataFromWebservice())。数据将被转换为字符串,而不是数组,如下所示:“[”item1”,“item2]”。
我需要解析数组吗?我认为问题在于中间的某个位置添加了引号,因此数据被识别为字符串而不是数组。
提前致谢!
javascript.js
var myArray = new Array();
function sendDataToWebservice() {
// Create the JSON to send to the webservice
var jsonData = {
"action": actionName,
"array": myArray
};
// Send the data
$.ajax({
url: "/xaction/",
type: 'POST',
data: JSON.stringify(jsonData),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: function (msg) {
// ...
}
});
}
function reveiveDataFromWebservice() {
// Receive the data
jQuery.getJSON("/webservice/getdata", function (returningData) {
if (returningData.success) {
array= returningData.array;
}
});
webservice.java
private void handleDataFunction(inputData) {
// Create a map for the parameters
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
// Create the query string
String query = "my sql query";
// Here I want to retrievethe array as a String to store it in the db
JsonArray jsonArray = currentAntwortFeld.get("array").getAsJsonArray();
// Add the array as an String to the sql parameters
namedParameters.addValue("arraydbfield", jsonArray.toString())
// Execute the sql query
factory.executeUpdate(query, namedParameters);
}
最佳答案
JSON.parse() 会将包含数组的字符串转换为数组对象。
myArray = JSON.parse(myString)
不知道为什么 jQuery 还没有为你做这件事。我认为这就是 $.getJSON()
的要点。但我不使用 jQuery,所以我真的不知道。
关于javascript - 通过 JSON 向 SQL 数据库发送和接收数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45954950/