How to get the number of elements that a JSON has with GSON in Java?

0

From the Front-end I send the file JSON , then in the Servlet , through GSON I transform it into an object:

    PrintWriter out = response.getWriter();
    String texto = request.getReader().readLine();
    Gson gson = new Gson();
    json1 = gson.fromJson(texto, Reserva.class);

What I want to do is post the amount of elements that the JSON file has. Or post the amount of elements that the Java object contains ( json1 ).

This is the JSON :

{
  "hot": "1",
  "numN": "1",
  "tipH": "camasimple ",
  "fechl": "2018-05-24",
  "num": "1",
  "numa": "1"
}

Greetings.

    
asked by TOMAS 23.05.2018 в 20:50
source

1 answer

0

I have this example that can help you:

public void listarJson(){
        String urlstr="http://localhost:8080/JavaWebServiceServerCRUD/rest/empleados/json/listarempleados";
        try{
            URL url = new  URL(urlstr);
            InputStream is = url.openStream();     
            JsonReader rdr=Json.createReader(new InputStreamReader(is, "UTF-8"));
            JsonArray results= rdr.readArray();
            Iterator<?> iterator = results.iterator();
            while(iterator.hasNext()){
                JsonObject jsonObject = (JsonObject) iterator.next();
                System.out.println("JSON-> El id es: "+jsonObject.get("id").toString().toUpperCase()+", el nombre es: "+jsonObject.get("nombre").toString().toUpperCase()+", el puesto es: "+jsonObject.get("puesto").toString().toUpperCase());
            }
        }catch (Exception e) {
            e.getMessage();
            e.printStackTrace();
        }
    }

As you can see, use an iterator:

Iterator<?> iterator = results.iterator();
    
answered by 24.05.2018 в 02:58