J'essaie d'imprimer la liste des entreprises.Parsing JSON Array
Mon objet JSON:
{
"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());
}
}
}
Erreur:
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
Juste une remarque: vous devez factoriser vos noms avant de mettre votre code dans la production. ;) - 'String age = (Chaîne) object.get (" Auteur ");' ... – Thomas
Il est dit exactement dans le message d'erreur: vous ne pouvez pas lancer un 'ArrayList' à un' JSONArray'. Pouvez-vous faire quelque chose comme ça peut-être? : 'ArrayList msg = object.get (" Liste des sociétés ");' – TW80000
Comment analysez-vous réellement la chaîne JSON? Votre méthode ne fait pas de véritable analyse - cela a déjà été fait lorsque vous avez créé cette instance initiale de 'JSONObject'. – Thomas