Hola, hallamos la respuesta a tu pregunta, has scroll y la obtendrás un poco más abajo.
Ejemplo 1: decodificar el archivo json en el tutorial de Java
packagecom.howtodoinjava.demo.jsonsimple;importjava.io.FileWriter;importjava.io.IOException;importorg.json.simple.JSONArray;importorg.json.simple.JSONObject;publicclassWriteJSONExample@SuppressWarnings("unchecked")publicstaticvoidmain(String[] args )//First EmployeeJSONObject employeeDetails =newJSONObject();
employeeDetails.put("firstName","Lokesh");
employeeDetails.put("lastName","Gupta");
employeeDetails.put("website","howtodoinjava.com");JSONObject employeeObject =newJSONObject();
employeeObject.put("employee", employeeDetails);//Second EmployeeJSONObject employeeDetails2 =newJSONObject();
employeeDetails2.put("firstName","Brian");
employeeDetails2.put("lastName","Schultz");
employeeDetails2.put("website","example.com");JSONObject employeeObject2 =newJSONObject();
employeeObject2.put("employee", employeeDetails2);//Add employees to listJSONArray employeeList =newJSONArray();
employeeList.add(employeeObject);
employeeList.add(employeeObject2);//Write JSON filetry(FileWriter file =newFileWriter("employees.json"))
file.write(employeeList.toJSONString());
file.flush();catch(IOException e)
e.printStackTrace();
Ejemplo 2: decodificar el archivo json en el tutorial de Java
packagecom.howtodoinjava.demo.jsonsimple;importjava.io.FileNotFoundException;importjava.io.FileReader;importjava.io.IOException;importorg.json.simple.JSONArray;importorg.json.simple.JSONObject;importorg.json.simple.parser.JSONParser;importorg.json.simple.parser.ParseException;publicclassReadJSONExample@SuppressWarnings("unchecked")publicstaticvoidmain(String[] args)//JSON parser object to parse read fileJSONParser jsonParser =newJSONParser();try(FileReader reader =newFileReader("employees.json"))//Read JSON fileObject obj = jsonParser.parse(reader);JSONArray employeeList =(JSONArray) obj;System.out.println(employeeList);//Iterate over employee array
employeeList.forEach( emp ->parseEmployeeObject((JSONObject) emp ));catch(FileNotFoundException e)
e.printStackTrace();catch(IOException e)
e.printStackTrace();catch(ParseException e)
e.printStackTrace();privatestaticvoidparseEmployeeObject(JSONObject employee)//Get employee object within listJSONObject employeeObject =(JSONObject) employee.get("employee");//Get employee first nameString firstName =(String) employeeObject.get("firstName");System.out.println(firstName);//Get employee last nameString lastName =(String) employeeObject.get("lastName");System.out.println(lastName);//Get employee website nameString website =(String) employeeObject.get("website");System.out.println(website);
Si crees que te ha sido de provecho nuestro artículo, sería de mucha ayuda si lo compartes con el resto programadores de esta manera contrubuyes a dar difusión a esta información.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)