在Java中将javascript数组转换为二维对象数组

时间:2016-03-30 13:16:21

标签: javascript java servlets multidimensional-array

我使用ajax to servlet

传递了这样的二维数组
var data = [["BSC","Name","Code"],[34,"dfg4",34],[345,"3dg4sdfd",345],[234,"dfg4","34f"],[23,"dfg4","s34"],[23,"dg","wdr3"],[234,244,"drydr"]];

$.ajax({
        url: './SubmitSheet',
        type: 'POST',
        data: {'json': JSON.stringify(data)},
        success: function () {
    }
});

在servlet中,我需要将值检索到二维数组 我尝试过使用

String data[] = request.getParameterValues("json");

但它将所有值都放入0索引(data [0])

2 个答案:

答案 0 :(得分:0)

你的代码应该是:

String data = request.getParameter("json");

您需要使用gson

解析字符串

答案 1 :(得分:-1)

尝试这种方法。根据需要更改输入值。

private static void jsArrayToJavaArray(){
    String input = "[[\"BSC\",\"Name\",\"Code\"],[34,\"dfg4\",34]," +
            "[345,\"3dg4sdfd\",345],[234,\"dfg4\",\"34f\"],[23,\"dfg4\",\"s34\"]," +
            "[23,\"dg\",\"wdr3\"],[234,244,\"drydr\"]]";

    input = input.substring(2,input.lastIndexOf("]"));
    input = input.substring(0,input.lastIndexOf("]"));

    String outerArr[] = input.split("],\\[");
    String output[][]= new String[outerArr.length][];
    for(int i=0;i<outerArr.length;i++){
        output[i] = outerArr[i].split(",");
    }

    //print results
    for(int i=0;i<output.length;i++){
        for(int j=0;j<output[i].length;j++){
            System.out.println(output[i][j]);
        }
    }
}