How to consume a JSON... GET and POST

This page shows how to consume a JSON (GET and POST)

How to consume a JSON and populates the data in a table

Using the method: Core.httpGet (String url, String [] mediaType, Class result) ... the script makes a Http Get request and returns a JSON as a String, then it reads the returned JSON and populates the data in the table shown in the figure below

 public Response actionIndex() throws IOException, IllegalArgumentException, IllegalAccessException{

Resttest model = new Resttest();
model.load();
ResttestView view = new ResttestView();

String json = Core.httpGet("https://jsonplaceholder.typicode.com/posts", new String[] {}, String.class);

model.setTable_1(new ArrayList<Resttest.Table_1>());

JSONArray aux1 = new JSONArray(json);

for(int i = 0; i < aux1.length(); i ++) {
  JSONObject obj = aux1.getJSONObject(i);
  Resttest.Table_1 row = new Resttest.Table_1();
  row.setQuote(obj.getString("body"));
  row.setSequence("" + obj.getInt("id"));
  row.setTitulo(obj.getString("title"));
  row.setUserid("" + obj.getInt("userId"));

model.getTable_1().add(row);
}
/*----#end-code----*/

view.setModel(model);

return this.renderView(view);
}

How to consume a JSON/POST

The script below allows you to collect the data (Name, Job) of the form shown in the fig. 2 and then make an HTTP POST, invoking an API ... If the operation is successful, it returns the JSON as a String and prints it in a message INFO.

public Response actionGuardar() throws IOException, IllegalArgumentException, IllegalAccessException{

Restpost model = new Restpost();
model.load();

String dados = "{\"name\": \"" + model.getNome() + "\",\"job\": \"" + model.getJob() + "\"}";

javax.ws.rs.core.Response response = 
Core.httpPost(
"https://reqres.in/api/users", 
dados, 
new String[] {"application/json; charset=UTF-8"}, 
"application/josn", 
javax.ws.rs.core.Response.class
);

if(response.getStatus() == 200 || response.getStatus() == 201) {
    String resultPost = response.readEntity(String.class);
    Core.setMessageSuccess();
    Core.setMessageInfo("JSONResult: " + resultPost);
}else {
    Core.setMessageError();
}

return this.redirect("mywebapp","Restpost","index", this.queryString());
}

Last updated