Return only the first data from a JSON and JAVA array

Asked

Viewed 755 times

0

I have a project where I search the database via JSON, to export this data in Excel format. I am adding a new search, however I have a string array, but I cannot bring the database data back to me only the first data of this array.

for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject js = jsonArray.getJSONObject(i);
    JSONObject js2 = js.getJSONObject("cliente").optJSONObject("enderecoList").getJSONObject("municipio");
    JSONObject jsUnidade = js.getJSONObject("unidade");
    JSONObject jsUnidadePai = jsUnidade.getJSONObject("unidadePai");
    JSONObject jsCliente = js.getJSONObject("cliente");
    JSONObject jsApl = js.getJSONObject("apl");
    JSONObject jsSetor = js.getJSONObject("setor");

I would like it to return me only the first data found in the array getJSONObject("municipio")

It is not written getJSONArray("municipio"), because I cannot give a getString to show the value returned.

I am beginner in java and JSON.

  • but if you want it to return only the first data found in the array not to do something like for(int i = 0; i < 2; i++) so just loop once and return only the first?

  • But I need the for to return me the other data.

  • 1

    Could you show the structure of this JSON? But if you only want the first item in the list try this way: Jsonobject js = jsonArray.getJSONObject(0);

  • But not for you are determining that the Object js receives jasonArray.getJSONObject(i) so if in yours is I’m just is (int i = 0; i < 1; i++) the value of I will only be 0 so picking up the first record found

  • I did this, but it exports the Excel file without a single data.

1 answer

0


What you need to do is change the code to get the municipio as a Jsonarray, and if you need to take only the first element, use the getJSONObject method, as the example below:

JSONObject js2 = js.getJSONObject("cliente").optJSONObject("enderecoList")
           .getJSONArray("municipio").getJSONObject(0);

But it would still be better to bring each element at a time. Something like this:

JSONObject endList = js.getJSONObject("cliente").optJSONObject("enderecoList");
if(js != null) {
    JSONArray jsMunicipios = endList.getJSONArray("municipio");
    if(jsMunicipios.length() > 0) {
        JSONObject primeiroMunicipio = jsMunicipios.getJSONObject(0);
        // Imprime ou usa o primeiro Municipio aqui
    }
}

Because this way you have more control over the code and debugging possible errors that can happen when reading JSON.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.