简体   繁体   中英

How to parse array into array JSON

first of all I wanted to know if the structure of the json is correct, you can find the JSON here:

http://demo8461125.mockable.io/whitemage

if it is correct I would like to know how to parse "PANINI" , is an array inside an array "tipopietanza"

 JSONArray arr = response.getJSONArray("pietanze");
                            for (int i = 0; i < arr.length(); i++)
                            {

                                JSONArray pietanze = response.getJSONArray("PANINI");
                                List<Pietanze> listapietanze =new ArrayList<>(pietanze.length());

                                for(int j=0;j<pietanze.length();j++)
                                {
                                    Pietanze tmp = new Pietanze();
                                    tmp.setNome(pietanze.getJSONObject(j).getString("nomepietanza"));
                                    listapietanze.add(tmp);
                                }
                                expandableListDetail.put(arr.getJSONObject(i).getString("tipopietanza"), listapietanze);
                            }

Yes, it should work, but I suggest just use Gson :

Type type = new TypeToken<List<TipiPaniniAndServizi>>(){}.getType();
List<TipiPaniniAndServizi> tipiPaniniAndServizi = gson.fromJson(json, type);

And save your time from manipulate JSON , just think about your java objects.

JSON structure is okay.

You need to do minor changes in your code for getting list properly.

JSONArray arr = response.getJSONArray("pietanze");
for (int i = 0; i < arr.length(); i++) {
    JSONObject jsonObject = arr.getJSONObject(i);

    if(jsonObject.has("PANINI")) {
        JSONArray paniniJsonArray = jsonObject.getJSONArray("PANINI");
        List<Panini> listPanini = new ArrayList<>();

        for (int j = 0; j < paniniJsonArray.length(); j++) {
            Panini panini = new Panini();
            panini.setId(paniniJsonArray.getJSONObject(j).getString("id"));
            panini.setNomepietanza(paniniJsonArray.getJSONObject(j).getString("nomepietanza"));
            panini.setPrezzo(paniniJsonArray.getJSONObject(j).getString("prezzo"));
            listPanini.add(panini);
        }
        expandableListDetail.put(arr.getJSONObject(i).getString("tipopietanza"), listPanini);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM