Convert Gson to ListObject

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 (CategoryItem) 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 settings should I make to create this same list using the Gson library?

    
asked by anonymous 09.05.2018 / 18:41

1 answer

1

implement Serializable in the CategoryItem class, then just use this:

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

Note that if it is an instance of json's you should mount an object that groups the occurrences, it should be serializable and the occurrence does not:

public class CategoriaItemArrayList implements Serializable {

    private ArrayList<CategoriaItem> categoriaItem;
  

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

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

listaCategorias.get(0);
    
01.07.2018 / 13:03