Khushi Khushi - 1 year ago 93
Java Question

JSONException while retrieving elements in JSONArray (from json string)

I am having a JSON string (jsonString):


jsonString is an array and I have to retrieve Name elements from it
I am using below code:

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

System.out.println("jsonString"+ jsonString);
JSONObject jsonObj = new JSONObject();

JSONArray lineItems = jsonObj.getJSONArray(jsonString);
for (Object o : lineItems) {
JSONObject jsonLineItem = (JSONObject) o;
String name = jsonLineItem.getString("Name");
String valueDate = jsonLineItem.getString("ValueDate");

But I am getting below error:

net.sf.json.JSONException: JSONObject["[\"[{\"Name\":\"name.pdf\",\"ValueDate\":\"2016-08-30T22:00:00+0000\"}]\"]"] is not a JSONArray.

at net.sf.json.JSONObject.getJSONArray( ~[json-lib-2.4.jar:na]

Can anybody help me in this?

I used JSONArray lineItems = JSONArray.fromObject(jsonString); to come over above error suggested by qxz and used below code to loop through JSONArray

JSONArray lineItems = JSONArray.fromObject(listDocToSendJson);
for (int i = 0; i < lineItems.size(); i++) {
JSONObject jsonObj = lineItems.getJSONObject(i);
String name = jsonObj.getString("Name");
String valueDate = jsonObj.getString("ValueDate");



for (Object object : lineItems) {
JSONObject jsonStr = (JSONObject)JSONSerializer.toJSON(object);
System.out.println(" name is --"+jsonStr.get("Name"));
System.out.println(" value is ---"+jsonStr.get("ValueDate"));

Both are giving errors
1) net.sf.json.JSONException: JSONArray[0] is not a JSONObject.

2) java.lang.ClassCastException: net.sf.json.JSONArray cannot be cast to net.sf.json.JSONObject

Please suggest..


Answer Source

Try this it should work .. just to add your json string had a problem i have corrected that as well it should as


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONTest {
      public static void main(String[] args) {
            String jsonString ="[{\"Name\":\"name.pdf\",\"ValueDate\":\"2016-08-30T22:00:00+0000\"}]";

            System.out.println("jsonString" + jsonString);
            try {
                  JSONArray jsonArray = new JSONArray(jsonString);
                  for (int i=0;i<jsonArray.length();i++) {

                        JSONObject jsonObj = jsonArray.getJSONObject(i);
                        String name = jsonObj.getString("Name");
                        String valueDate = jsonObj.getString("ValueDate");
                        System.out.println("Name : "+name + "ValueDate : "+valueDate);
            } catch (JSONException e) {
                  // TODO Auto-generated catch block
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download