Skip to content

Instantly share code, notes, and snippets.

@leonardocordeiro
Created February 6, 2016 03:53
Show Gist options
  • Save leonardocordeiro/ca964eabb293f9d5236e to your computer and use it in GitHub Desktop.
Save leonardocordeiro/ca964eabb293f9d5236e to your computer and use it in GitHub Desktop.
FJ-57 servico medias
@Path("/mobile")
public void service() throws Exception {
BufferedReader reader = request.getReader();
StringBuilder sb = new StringBuilder();
String json;
while((json = reader.readLine()) != null) {
sb.append(json);
}
json = sb.toString();
String resultado = "" ;
if ( json != null ) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("list").getJSONObject(0).getJSONArray("aluno");
double media = 0;
double soma = 0;
int numeroDeAlunos = jsonArray.length();
String mediaFormatada = "0.00";
for(int i = 0; i < numeroDeAlunos; i++) {
double nota = 0;
JSONObject aluno = jsonArray.getJSONObject(i);
if(aluno.has("nota")) {
nota = aluno.getDouble("nota");
}
soma += nota;
}
if(numeroDeAlunos != 0) {
media = soma/numeroDeAlunos;
}
DecimalFormat format = new DecimalFormat("#.##");
mediaFormatada = format.format(media);
JSONStringer s = new JSONStringer () ;
s.object()
.key("media").value(mediaFormatada)
.key("quantidade").value(numeroDeAlunos)
.endObject() ;
resultado = s.toString() ;
} catch (JSONException e) {
throw new IllegalArgumentException(e);
}
}
PrintWriter out = response.getWriter() ;
out.println(resultado) ;
result.nothing();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment