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