Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

Tags:

java

json

I'm trying to parse below json file:

{"units":[{"id":42,               
   "title":"Hello World",          
    "position":1,
    "v_id":9,
    "sites":[[{"id":316,
      "article":42,
      "clip":133904
        }],
       {"length":5}]

   }, ..]}

This is what I have tried:

Object obj = null;
JSONParser parser = new JSONParser();
Object unitsObj = parser.parse(new FileReader("file.json");
JSONObject unitsJson = (JSONObject) unitsObj;

JSONArray units = (JSONArray) unitsJson.get("units");
Iterator<String> unitsIterator = units.iterator();
while(unitsIterator.hasNext()){         
    Object uJson = unitsIterator.next();
    JSONObject uj = (JSONObject) uJson;
    obj =  parser.parse(uj.get("sites").toString());
    JSONArray jsonSites = (JSONArray)  obj;

    for(int i=0;i<jsonSites.size();i++){
     JSONObject site = (JSONObject)jsonSites.get(i); // Exception happens here.
     System.out.println(site.get("article");
    }
}

The code is not working when I try to parse the inner json array, so I get:

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

The exception is pointing to this line:

JSONObject site = (JSONObject)jsonSites.get(i);

Any help? tnx.

like image 255
tokhi Avatar asked Aug 26 '13 08:08

tokhi


3 Answers

I've found a working code:

JSONParser parser = new JSONParser();
Object obj  = parser.parse(content);
JSONArray array = new JSONArray();
array.add(obj);

If you don't need the array (like the author), you can simply use

JSONParser parser = new JSONParser();
Object obj  = parser.parse(content);
like image 88
Danon Avatar answered Sep 17 '22 14:09

Danon


The first element of the sites array is an array, as you can see indenting the JSON:

{"units":[{"id":42,               
    ...
    "sites":
    [
      [
        {
          "id":316,
          "article":42,
          "clip":133904
        }
      ],
      {"length":5}
    ]
    ...
}

Therefore you need to treat its value accordingly; probably you could do something like:

JSONObject site = (JSONObject)(((JSONArray)jsonSites.get(i)).get(0));
like image 34
cyberz Avatar answered Sep 20 '22 14:09

cyberz


this worked:

System.out.println("resultList.toString() " + resultList);
            org.json.JSONObject obj = new JSONObject(resultList);
            org.json.JSONArray jsonArray = obj.getJSONArray(someField);

            for(int i=0;i<jsonArray.length();i++){
                System.out.println("array is " + jsonArray.get(i));

            }
like image 43
arn-arn Avatar answered Sep 17 '22 14:09

arn-arn