如何摆脱错误:JSONArray [0]不是JSONObject

时间:2013-10-09 19:34:28

标签: java json

获取错误时,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"));
        }

数组包含一个值为:

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

任何评论都将不胜感激。

1 个答案:

答案 0 :(得分: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"));
}

而且,由于stafftrip是字符串,因此您需要使用getString()代替getInt()