Return only the first data of an array in JSON and JAVA

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, but I have a string array, but I can not get the data from the database so that it returns only the first data of that 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'd like it to return only the first data I found in the array getJSONObject("municipio")

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

I'm a beginner in java and JSON.

    
asked by anonymous 08.03.2017 / 21:48

1 answer

0

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

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

But still it would 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
    }
}

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

    
10.03.2017 / 04:54