0

收到错误消息,JSONArray[0] 不是 JSONObject,同时从 JSON 数组中获取对象(Java 代码行 #5)。

客户端的 jQuery

function setCosting(){
        var costingArray = {};
        costingArray = getCostingArray();
        var costingData = JSON.stringify(costingArray);
        alert(costingData);
        $.ajax({
            type:"POST",
            url:"/costApp/budgetline.do?action=setCosting",
            data:{"costingData": costingData},
            datatype:'json',
            success: function (msg) {
                if (msg) {
                    alert('success');
                }
            },
            error: function (msg) {
                alert('error');
            }

        });
    function getCostingArray() {
        var rows = $("table tbody tr");
        var dataset = [];
        rows.each(function(i, row){
            var rowset = {};
            var $row = $(row);
            rowset['travelType'] = $row.find('#travelType').val();
            rowset['staff'] = $row.find('#staff').val();
            rowset['trip'] = $row.find('#trip').val();
            dataset.push(rowset);
        });

        return dataset;
    }

    $('#save').click(function() {
        setCosting();
    });

Java 代码

Map mpVal = request.getParameterMap();    
JSONObject rootObj = new JSONObject(mpVal);
        JSONArray arrayObj = rootObj.getJSONArray("costingData");
        for(int m=0; m<arrayObj.length(); m++){
            **JSONObject costing = arrayObj.getJSONObject(m);**
            System.out.println(costing.getInt("travelType"));
            System.out.println(costing.getInt("staff"));
            System.out.println(costing.getInt("trip"));
        }

该数组包含一个具有以下值的元素:

[
    {
        "travelType": "1",
        "staff": "red",
        "trip": ""
    },
    {
        "travelType": "2",
        "staff": "blue",
        "trip": ""
    },
    {
        "travelType": "3",
        "staff": "green",
        "trip": ""
    }
]

任何评论将不胜感激。

4

1 回答 1

1

由于该数组包含一个元素,其值本身就是一个数组,因此您需要

JSONArray arrayObj = rootObj.getJSONArray("costingData").getJSONArray(0);
for(int m=0; m<arrayObj.length(); m++){
    JSONObject costing = arrayObj.getJSONObject(m);
    System.out.println(costing.getString("travelType"));
    System.out.println(costing.getString("staff"));
    System.out.println(costing.getString("trip"));
}

而且,因为staffandtrip是您需要使用的字符串,getString()而不是getInt().

于 2013-10-09T19:39:39.567 回答