Home > OS >  Getting attribute values from JSON String in Java
Getting attribute values from JSON String in Java

Time:05-27

Hello I am building a Spring Boot app with Thymeleaf and I am receiving from an API a JSON that I have to put in the HTML page. This is the JSON:

{"mesaje":[{"data_creare":"202205191249","cif":"1111111111118","id_solicitare":"205804","detalii":"Erori de validare identificate la factura primita cu id_incarcare=205804","tip":"ERORI FACTURA","id":"9279339"}

This is what I have tried:

    String raspuns = service.getListaMesaje(zile, select);
     System.out.println("------------------------" raspuns);
       JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(raspuns).getAsJsonObject();
//String eroare = obj.get("eroare").getAsString();
String mesaje = obj.get("mesaje").getAsString();

        JSONObject responseObject = new JSONObject(raspuns);       
        JSONArray jsonArray = (JSONArray) responseObject.get("mesaje");
        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
        String dataCreare  = jsonObject.getString("data_creare");
       
        
        model.addAttribute("data_creare", dataCreare);

In the console the JSON prints but I get this error also in the console:

java.lang.IllegalStateException: null

Can someone show me an example how to extract the values from mesaje parent in the JSON ?

Thank you

CodePudding user response:

I suggest you to use gson library for that.

Then, after you added gson dependency in pom.xml, you can extract values from your JSON string with this few lines of code :

String raspuns = "{\"mesaje\":[{\"data_creare\":\"202205191249\",\"cif\":\"1111111111118\",\"id_solicitare\":\"205804\",\"detalii\":\"Erori de validare identificate la factura primita cu id_incarcare=205804\",\"tip\":\"ERORI FACTURA\",\"id\":\"9279339\"}]}";




 JsonObject jsonObject = new JsonParser().parse(raspuns).getAsJsonObject();
 JsonArray arr = jsonObject.getAsJsonArray("mesaje");
    for (int i = 0; i < arr.size(); i  ) {
        String data_creare = arr.get(i).getAsJsonObject().get("data_creare").getAsString();
        String cif = arr.get(i).getAsJsonObject().get("cif").getAsString();
        String id_solicitare = arr.get(i).getAsJsonObject().get("id_solicitare").getAsString();
        String detalii = arr.get(i).getAsJsonObject().get("detalii").getAsString();
        String tip = arr.get(i).getAsJsonObject().get("tip").getAsString();
        String id = arr.get(i).getAsJsonObject().get("id").getAsString();
        System.out.println(data_creare);
        System.out.println(cif);
        System.out.println(tip);
        System.out.println(id_solicitare);
        System.out.println(detalii);
        System.out.println(id);
}
  • Related