21

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.

1
  • In sites there seems to be an array in an array, note the double square brackets. Commented Aug 26, 2013 at 8:50

10 Answers 10

32

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Although this is exact opposite to what the question asked, it solved my problem i.e. convert JSONObject to JSONArray...So +1 from my side
8

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

2 Comments

I still get the same exception: JSONObject cannot be cast to JSONArray
Thank you, your answer helps me to know the problem then I solved it by creating a nested loop while j<site.length() to get site.get(j).toString()
2

JSONObject site=jsonSites.getJSONObject(i) should work out

3 Comments

there is no getJSONObject method for JSONArray
I'm using this: org.json.simple.JSON
so why don't try the one i introduced?
2

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

            }

Comments

1
JSONObject obj=(JSONObject)JSONValue.parse(content); 
JSONArray arr=(JSONArray)obj.get("units"); 
System.out.println(arr.get(1));  //this will print {"id":42,...sities ..}

@cyberz is right but explain it reverse

Comments

1

You can first read the whole content of file into a String.

FileInputStream fileInputStream = null;
String data="";
StringBuffer stringBuffer = new StringBuffer("");
try{
    fileInputStream=new FileInputStream(filename);
    int i;
    while((i=fileInputStream.read())!=-1)
    {
        stringBuffer.append((char)i);
    }
    data = stringBuffer.toString();
}
catch(Exception e){
        LoggerUtil.printStackTrace(e);
}
finally{
    if(fileInputStream!=null){  
        fileInputStream.close();
    }
}

Now You will have the whole content into String ( data variable ).

JSONParser parser = new JSONParser();
org.json.simple.JSONArray jsonArray= (org.json.simple.JSONArray) parser.parse(data);

After that you can use jsonArray as you want.

Comments

1

If you want to re-filter the json data you can use following method. Given example is getting all document data from couchdb.

{
    Gson gson = new Gson();
    String resultJson = restTemplate.getForObject(url+"_all_docs?include_docs=true", String.class);
    JSONObject object =  (JSONObject) new JSONParser().parse(resultJson);
    JSONArray rowdata = (JSONArray) object.get("rows");   
    List<Object>list=new ArrayList<Object>();   
    for(int i=0;i<rowdata.size();i++) {
        JSONObject index = (JSONObject) rowdata.get(i);
        JSONObject data = (JSONObject) index.get("doc");
        list.add(data);      
    }
    // convert your list to json
    String devicelist = gson.toJson(list);
    return devicelist;
}

Comments

1
JSONObject site = (JSONObject)jsonSites.get(i); // Exception happens here.

The return type of jsonSites.get(i) is JSONArray not JSONObject. Because sites have two '[', two means there are two arrays here.

Comments

0

use your jsonsimpleobject direclty like below

JSONObject unitsObj = parser.parse(new FileReader("file.json");

Comments

0
JSONObject baseReq
LinkedHashMap insert = (LinkedHashMap) baseReq.get("insert");
LinkedHashMap delete = (LinkedHashMap) baseReq.get("delete");

2 Comments

Explain it please!
I have same code, that convert to LinkedHashMap., but suddenly its stop to work and return by get("...") scala.some.Map. do you know what can be the problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.