Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting JSONArray to List<Object>?

Tags:

java

json

gson

I'm trying deserializes a JSONArray to List. To do it I'm trying use Gson but I can't understand why doesn't works and all values of JSON are null.

How could I do this ?

JSON

{ "result" : [ 
      { "Noticia" : { 
            "created" : "2015-08-20 19:58:49",
            "descricao" : "tttttt",
            "id" : "19",
            "image" : null,
            "titulo" : "ddddd",
            "usuario" : "FERNANDO PAIVA"
          } },
      { "Noticia" : { 
            "created" : "2015-08-20 19:59:57",
            "descricao" : "hhhhhhhh",
            "id" : "20",
            "image" : "logo.png",
            "titulo" : "TITULO DA NOTICIA",
            "usuario" : "FERNANDO PAIVA"
          } }
    ] }

Deserializes

List<Noticia> lista = new ArrayList<Noticia>();
                            Gson gson = new Gson();
                            JSONArray array = obj.getJSONArray("result");

                            Type listType = new TypeToken<List<Noticia>>() {}.getType();
                            lista = gson.fromJson(array.toString(), listType);

                            //testing - size = 2 but value Titulo is null
                            Log.i("LISTSIZE->", lista.size() +"");
                            for(Noticia n:lista){
                                Log.i("TITULO", n.getTitulo());
                            }

Class Noticia

public class Noticia implements Serializable {
    private static final long serialVersionUID = 1L;

    private Integer id;
    private String titulo;
    private String descricao;
    private String usuario;
    private Date created;
    private String image;
like image 717
FernandoPaiva Avatar asked Aug 21 '15 06:08

FernandoPaiva


People also ask

How can I turn a JSONArray into a JSON object?

We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.

Can we convert JSON array to list in Java?

We can convert a JSON array to a list using the ObjectMapper class. It has a useful method readValue() which takes a JSON string and converts it to the object class specified in the second argument.

How do I get items from JSONArray?

JSONArray jsonArray = (JSONArray) jsonObject. get("contact"); The iterator() method of the JSONArray class returns an Iterator object using which you can iterate the contents of the current array.

Is JSONArray a JSON object?

JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.


3 Answers

There are two problems with your code :

  1. First is that you are using a getJsonArray() to get the array, which isn't part of Gson library, you need to use getAsJsonArray() method instead.
  2. Second is that you are using array.toString() which isn't obvious because for the fromJson method you need a jsonArray as parameter and not String and that will cause you parse problems, just remove it.

And use the following code to convert your jsonArray to List<Noticia> :

Type type = new TypeToken<List<Noticia>>() {}.getType();
List<Noticia> lista = gson.fromJson(array, type);

And your whole code will be:

Gson gson = new Gson();
JSONArray array = obj.getAsJsonArray("result");

Type type = new TypeToken<List<Noticia>>() {}.getType();
List<Noticia> lista = gson.fromJson(array, type);

//testing - size = 2 but value Titulo is null
Log.i("LISTSIZE->", lista.size() +"");
for(Noticia n:lista){
   Log.i("TITULO", n.getTitulo());
}
like image 85
cнŝdk Avatar answered Oct 16 '22 08:10

cнŝdk


You parse json, that looks like

{ "result" : [ 
  { 
        "created" : "2015-08-20 19:58:49",
        "descricao" : "tttttt",
        "id" : "19",
        "image" : null,
        "titulo" : "ddddd",
        "usuario" : "FERNANDO PAIVA"
   },
  { 
        "created" : "2015-08-20 19:59:57",
        "descricao" : "hhhhhhhh",
        "id" : "20",
        "image" : "logo.png",
        "titulo" : "TITULO DA NOTICIA",
        "usuario" : "FERNANDO PAIVA"
      }
] }

You need to make another object Item and parse a list of them.

public class Item{
    Noticia noticia; 
}

Or you can interate through JSONArray, get field "noticia" from each then parse Noticia object from given JSONObject.

like image 41
ziviland Avatar answered Oct 16 '22 06:10

ziviland


Noticia.java

public class Noticia {
    private String created;
    private String descricao;
    private String id;
    private String image;
    private String titulo;
    private String usuario;
    public String getCreated() {
        return created;
    }
    public void setCreated(String created) {
        this.created = created;
    }
    public String getDescricao() {
        return descricao;
    }
    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getImage() {
        return image;
    }
    public void setImage(String image) {
        this.image = image;
    }
    public String getTitulo() {
        return titulo;
    }
    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }
    public String getUsuario() {
        return usuario;
    }
    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }
    @Override
    public String toString() {
        return "Noticia [created=" + created + ", descricao=" + descricao
                + ", id=" + id + ", image=" + image + ", titulo=" + titulo
                + ", usuario=" + usuario + "]";
    }
}

Result.java

public class Result {
    private Noticia Noticia;

    public Noticia getNoticia() {
        return Noticia;
    }

    public void setNoticia(Noticia noticia) {
        Noticia = noticia;
    }

    @Override
    public String toString() {
        return "Result [Noticia=" + Noticia + "]";
    }

}

Item.java

import java.util.List;

public class Item {
    private List<Result> result;

    public List<Result> getResult() {
        return result;
    }

    public void setResult(List<Result> result) {
        this.result = result;
    }

    @Override
    public String toString() {
        return "Item [result=" + result + "]";
    }
}

Main.java

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.testgson.beans.Item;

public class Main {
    private static Gson gson;

    static {
        gson = new GsonBuilder().create();
    }

    public static void main(String[] args) {
        String j = "{\"result\":[{\"Noticia\":{\"created\":\"2015-08-20 19:58:49\",\"descricao\":\"tttttt\",\"id\":\"19\",\"image\":null,\"titulo\":\"ddddd\",\"usuario\":\"FERNANDO PAIVA\"}},{\"Noticia\":{\"created\":\"2015-08-20 19:59:57\",\"descricao\":\"hhhhhhhh\",\"id\":\"20\",\"image\":\"logo.png\",\"titulo\":\"TITULO DA NOTICIA\",\"usuario\":\"FERNANDO PAIVA\"}}]}";
        Item r = gson.fromJson(j, Item.class);
        System.out.println(r);
    }
}

Final result

Item [result=[Result [Noticia=Noticia [created=2015-08-20 19:58:49, descricao=tttttt, id=19, image=null, titulo=ddddd, usuario=FERNANDO PAIVA]], Result [Noticia=Noticia [created=2015-08-20 19:59:57, descricao=hhhhhhhh, id=20, image=logo.png, titulo=TITULO DA NOTICIA, usuario=FERNANDO PAIVA]]]]
like image 1
Saurabh Avatar answered Oct 16 '22 08:10

Saurabh