Convert Gson to List<Object>

Asked

Viewed 187 times

0

I’m starting to learn how to use the Gson library in my code and need to create a list of objects from a Json file.

Json: [{"id":1,"cat":"teste","icone":"icone"},{"id":2,"cat":"teste2","icone":"icone2"}]

of this file two Objects (Categoriaitem) are generated and added to the list using this code:

    public static List<CategoriaItem> jsonCategoria(String json) {
    List<CategoriaItem> list = new ArrayList<>();

    try {
        JSONArray jsonBase = new JSONArray(json);


        for (int i = 0; i < jsonBase.length(); i++) {
            JSONObject object = jsonBase.getJSONObject(i);
            CategoriaItem categoria = new CategoriaItem(object);
            list.add(categoria);
        }

What adjustments should be made to create this same list using the Gson library?

1 answer

1


implement Serializable in the Categoriaitem class, then just use it like this:

CategoriaItem categoria = gson.fromJson("{id:1,cat:teste,icone:icone}", CategoriaItem.class);

note that if it is an occurrence of json`s Oce must assemble an object that groups the occurrences, it must be serializable and the occurrence must not:

public class CategoriaItemArrayList implements Serializable {

    private ArrayList<CategoriaItem> categoriaItem;

Categoriaitemarraylist listCategories = gson.fromJson("[{id:1,cat:test,icone:icone},{id:2,cat:teste2,icone:icone2}]", Categoriaitemarraylist.class);

and to access the list object you already know use get(0)

listaCategorias.get(0);

Browser other questions tagged

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