SERICON BANG
SERICON BANG

Reputation: 29

How to get rid of the error: JSONArray[0] is not a JSONObject

Getting the error, JSONArray[0] is not a JSONObject, while getting an object from the JSON array (Java code line #5).

jQuery on client side

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 Code

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"));
        }

The array contains a sigle element with the value:

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

Any comment would be appreciated.

Upvotes: 0

Views: 5983

Answers (1)

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

Since, the array contains a single element with a value that's an array itself, you need

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"));
}

And, since staff and trip are strings you need to use getString() instead of getInt().

Upvotes: 1

Related Questions