簡體   English   中英

通過JSON向SQL數據庫發送和接收數組

[英]Sending and receiving an array to a sql database via JSON

我在要發送到Java Web服務的對象中放置了一個數組(請參見javascript.js-> sendDataToWebservice())。 Web服務繼續處理該數組(通過gson)並將其另存為String在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,所以我真的不知道。

為了從JSON轉換為SQL,我實現了以下步驟:

 let jsArray = [1,2,3,4] //Example array in JS
 let sqlArray = '{';
 jsArray.forEach(element=>sqlArray+=element+',')
 sqlArray = sqlArray.substring(0, sqlArray.length-1) + '}'

現在使用sqlArray適合SQL。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM