Search code examples
javaparsingsimplejson

Parsing JSON Array


I'm trying to print company list.

My JSON object:

{
    "Name": "crunchify.com",
    "Author": "App Shah",
    "Company List": [
        "Compnay: eBay",
        "Compnay: Paypal",
        "Compnay: Google"
    ]
}

code:

public class ProductTypeParser {

    public  void parseJson(JSONObject jsonObject) throws ParseException {



        JSONObject object = (JSONObject) jsonObject;
        String name = (String) object.get("Name");
        System.out.println(name);

        String age = (String) object.get("Author");
        System.out.println(age);

        //loop array        
        JSONArray msg = (JSONArray) object.get("Company List"); 
        Iterator<String> iterator = msg.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }       
    }
}

Error:

SEVERE: Servlet.service() for servlet [contextServlet] in context with path [/SpringSafeHouseService2.0] 
  threw exception [Request processing failed; nested exception is 
    java.lang.ClassCastException: java.util.ArrayList cannot be cast to org.json.simple.JSONArray] 
  with root cause java.lang.ClassCastException: java.util.ArrayList cannot be cast to org.json.simple.JSONArray

Solution

  • Json-simple (which you seem to be using although the version is missing so my information might be outdated) normally creates an instance of JSONArray (which extends ArrayList btw.) for arrays in json strings, i.e. your "Company List" field.

    However, you are also able to pass in a different ContainerFactory which might create a different List instance for arrays so that might be the reason your cast doesn't work (again there's too little information in your question to further comment on that).

    Finally, since you should get a List anyways it should be safe to cast to that:

    List<?> msg = (List<?>) object.get("Company List");