Convert returned JSON string to JSONArray

I have a web service that makes a database request, converts the result set to a JSON string, and returns a binding to the client. This is the code for the converter (I got it from http://biercoff.com/nice-and-simple-converter-of-java-resultset-into-jsonarray-or-xml/ ):

public static String convertToJSON(ResultSet resultSet)
        throws Exception {
    JSONArray jsonArray = new JSONArray();
    while (resultSet.next()) {
        int total_rows = resultSet.getMetaData().getColumnCount();
        JSONObject obj = new JSONObject();
        for (int i = 0; i < total_rows; i++) {
            obj.put(resultSet.getMetaData().getColumnLabel(i + 1)
                    .toLowerCase(), resultSet.getObject(i + 1));
        }
        jsonArray.add(obj);
    }
    return jsonArray.toJSONString();
}

      

In the client application, when I print the returned string, it is in the following format:

[{"Column1":0.333333,"Column2":"FirmA"},{"Column1":0.666667,"Column2":"FirmB"}]

      

so far so good. The problem I am facing is converting the returned string to a JSON array. I've tried this:

JSONArray arr = new JSONArray(JSON_STRING);

      

but received the following error message: The JSONArray constructor in the JSONArray class cannot be applied to the given types. I tried to convert the JSON object first like this:

JSONObject obj = new JSONObject(JSON_STRING);

      

but got the following error: Incompatible types: String cannot be converted to Map. What am I doing wrong? Thank.

+3


source to share


3 answers


Apparently the problem was with the json library I was using. When i used

import org.json.JSONArray;

      

everything worked out well. I was able to convert the returned string to an array using



JSONArray arr = new JSONArray(JSON_STRING);

      

and for iterating over the values ​​I used, the code given in this answer: Accessing the elements of elements in a JSONArray from Java , which I reproduce here for simplicity:

for (int i = 0; i < arr.length(); ++i) {
    JSONObject rec = arr.getJSONObject(i);
    int id = rec.getInt("id");
    String loc = rec.getString("loc");
    // ...
}

      

+1


source


well you need to do it this way, for example



String jsonText = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
        try {

            JSONArray array = new JSONArray(jsonText);
            System.out.println(array);
            System.out.println(array.length());

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

      

0


source


Check if the library used is correct. The confusion is that org.json.simple is often suggested by the IDE as the default for JSONObject and JSONArray .

You can find a link to the latest jar for the org.json library above.

0


source







All Articles