Sto tentando di deserializzare un JSONArray in List. Per farlo sto provando ad usare Gson ma non riesco a capire perché non funzioni e tutti i valori di JSON sono nulli.Conversione di JSONArray in elenco <Object>?
Come posso fare questo?
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"
} }
] }
deserializza
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());
}
Classe 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;
Il fatto che si esegua array.toString() mi sembra strano. Considererei forse iterare su JSONArray e trasformare ogni elemento in oggetto Noticia? –
Non vedo il metodo getJSONArray su JsonObject (https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonObject.html) Si prega di leggere la mia risposta. Spero che dovrebbe risolvere il problema. – Atul