I have the following JSON text. How can I read it?
{"animal": { "type": "Panther", "name": "Sylvester", "age": 12 }}
I've tried to do this but it doesn't work.
It throws this Exception
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray at Json_to_XML.main(Json_to_XML.java:31)
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':Json_to_XML.main()'. Process 'command 'C:/Program Files/Java/jdk1.8.0_181/bin/java.exe'' finished with non-zero exit value 1
public static void main(String[] args)
{
//JSON parser object to parse read file
JSONParser jsonParser = new JSONParser();
try {
String ruta ="C:\\Users\\Usuari\\Desktop\\documento.json";
Object obj = jsonParser.parse (new FileReader (ruta));
JSONObject jsonObject = (JSONObject) obj;
String tipo = (String) jsonObject.get("type");
System.out.println(tipo);
String nombre = (String) jsonObject.get("name");
System.out.println(nombre);
Long edad = (Long) jsonObject.get("age");
System.out.println(edad);
JSONArray leng= (JSONArray) jsonObject.get("animal");
Iterator iterator =leng.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
jsonObject.get("tipo")to return? There is notipokey in JSON you provided. Same about other keys.{}represents object,[]represents array."animal": { .. }holds object and that is whatjsonObject.get("animal")returns. You can't cast it to array (I don't know why would you even want to).