How to parse json to class objects in java?

1

I'm trying to consume an api with java I use Apache's httpClient library, it consumes me well and shows me the result and JSON all right up there, now the question is that I have a class with the attributes and when trying to obtain the data to make the cast generates an error and I do not know how to solve, here the java code:

CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpget = new HttpGet("http://localhost:50760/api/BockChapters");

        System.out.println("Executing request " + httpget.getRequestLine());

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(
                    final HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };

        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);

    } catch (FileNotFoundException e) {
        //manejo de error
    } catch (IOException e) {
        //manejo de error
    } catch (ParseException e) {
        //manejo de error
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            Logger.getLogger(JSON.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

this is the result:

[{"Numbre":1,"Title":"Hola Mundo1","Pages":222},{"Numbre":2,"Title":"Hola Mundo2","Pages":222},{"Numbre":3,"Title":"Hola Mundo3","Pages":222},{"Numbre":4,"Title":"Hola Mundo4","Pages":222},{"Numbre":5,"Title":"Hola Mundo5","Pages":222},{"Numbre":6,"Title":"Hola Mundo6","Pages":222},{"Numbre":7,"Title":"Hola Mundo7","Pages":222},{"Numbre":8,"Title":"Hola Mundo8","Pages":222}]

the class I want to cast is this

private int Numbre;

public String Title;

public int Pages;

public BockChapter() {
}

public BockChapter(int Numbre, String Title, int Pages) {
    this.Numbre = Numbre;
    this.Title = Title;
    this.Pages = Pages;
}

e tried to do the casting using a JSON library is called json-simple I do it this way

JSONParser parse = new JSONParser();
        Object obj = parse.parse(responseBody);
        JSONObject objson = (JSONObject) obj;
        String blog = (String) objson.get("Title");
        System.out.println(blog);

the error that throws me is the following

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to net.sf.json.JSONObject

and the error refers to the line

JSONObject objson = (JSONObject) obj;

could someone tell me how to fix this error or what else could be done

    
asked by Jhonny Luis 10.10.2017 в 21:30
source

4 answers

1

Assuming you have a POJO like the following

public class Persona {

    private String nombre;

    private String edad;

    //getters
    //setters
}

You could use ObjectMapper

ObjectMapper mapper = new ObjectMapper();

String respuesta = "{"nombre": "nombre", "edad": 99}";
Persona persona = mapper.readValue(respuesta, Persona.class);

String respuesta = "[{"nombre": "nombre", "edad": 99}]";
List<Persona> personas = mapper.readValue(respuesta, new TypeReference<List<Persona>>(){});
    
answered by 14.10.2017 в 07:21
1

Good morning,

I for the treatment of json use com.fasterxml.jackson .

In your case, the POJO would be as follows:

import com.fasterxml.jackson.annotation.JsonProperty;

public class BockChapter {

    @JsonProperty(value = "Numbre")
    private int number;

    @JsonProperty(value = "Title")
    private String title;

    @JsonProperty(value = "Pages")
    private int pages;

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    @Override
    public String toString() {
        return "Libro [number=" + number + ", title=" + title + ", pages=" + pages + "]";
    }   
}

I added the @JsonProperty annotation so that the names of the fields meet the standards in java.

The code for parsing the response in an array of objects is as follows:

String response = "[{\"Numbre\":1,\"Title\":\"Hola Mundo1\",\"Pages\":222},{\"Numbre\":2,\"Title\":\"Hola Mundo2\",\"Pages\":222},{\"Numbre\":3,\"Title\":\"Hola Mundo3\",\"Pages\":222}]";

        ObjectMapper mapper = new ObjectMapper();

        try {
            List<BockChapter> libros = mapper.readValue(response, mapper.getTypeFactory().constructCollectionType(List.class, BockChapter.class));
            System.out.println(libros);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

In this case, being a list, we have to specify the type of collection to which we want to parse the answer.

I hope this helps you.

Greetings

    
answered by 15.10.2017 в 12:27
0

The error indicates that what you are getting is an Array (JSONArray) and that can not be converted to JSONObject. So try to convert it to JSONArray and handle the information with the methods that that class provides you. You can try what is mentioned here and maybe see more information:

JSONParser parser = new JSONParser();
Object obj  = parser.parse(content);
JSONArray array = new JSONArray();
array.add(obj);
    
answered by 10.10.2017 в 22:15
0

One way to obtain the data would be as follows:

Librería Gson:

compile 'com.google.code.gson:gson:2.7'

Github: link

Documentation: link

*
 //Json de tu web service
        String json = "[{\"Numbre\":1,\"Title\":\"Hola Mundo1\",\"Pages\":222},{\"Numbre\":2,\"Title\":\"Hola Mundo2\",\"Pages\":222},{\"Numbre\":3,\"Title\":\"Hola Mundo3\",\"Pages\":222},{\"Numbre\":4,\"Title\":\"Hola Mundo4\",\"Pages\":222},{\"Numbre\":5,\"Title\":\"Hola Mundo5\",\"Pages\":222},{\"Numbre\":6,\"Title\":\"Hola Mundo6\",\"Pages\":222},{\"Numbre\":7,\"Title\":\"Hola Mundo7\",\"Pages\":222},{\"Numbre\":8,\"Title\":\"Hola Mundo8\",\"Pages\":222}]";




//Json parser | JsonElements
        JsonParser jsonParser = new JsonParser();
        //Parsear el json string a JsonObject, a JsonArray, a JsonPrimitive o a JsonNull
        JsonElement element = jsonParser.parse(json);
        //verificamos si es un json array
        if (element.isJsonArray())
        {
            //parseamos el elemento a json array
            JsonArray jsonArray = element.getAsJsonArray();
            //lista de tipo objeto para almacenar tus valores
            List<BockChapter> bockChapters = new ArrayList<>();
            //recorremos el json array
            for (int i=0;i<jsonArray.size();i++)
            {
                //obtenemos los objetos de la posición i
                JsonObject  objectJ = jsonArray.get(i).getAsJsonObject();
                //modelo para asignar tus valores
                BockChapter object = new BockChapter();
                //Obtenemos los valores
                object.setNumber(objectJ.get("Numbre").getAsString());
                object.setTitle(objectJ.get("Title").getAsString());
                object.setPages(objectJ.get("Pages").getAsInt());
                //agregamos a la lista
                bockChapters.add(object);
            }
            //verificamos la cantidad de registros obtenidos y agregados a la lista
            Log.e("List<BockChapter>: ","=> "+ bockChapters.size());
        }

Or:

try {
            //Recibimos el JSON Array
            JSONArray array = new JSONArray(json);
            //Recorremos el Array
            for (int i = 0; i <array.length(); i++)
            {
                //Obtenermos los objetos de la posición i
                JSONObject object = array.getJSONObject(i);
                BockChapter bockChapter = new BockChapter();
                //Obtenemos los valores del objeto en la posición indicada
                bockChapter.setNumber(object.getString("Numbre"));
                bockChapter.setTitle(object.getString("Title"));
                bockChapter.setPages(object.getInt("Pages"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

How to identify a JSONArray of a JSONObject? I leave the following image to you to detect when it is a JSON array or a JSON object.

    
answered by 10.10.2017 в 23:05