Valter Henrique Valter Henrique - 6 months ago 9
JSON Question

How to deserialize a list using GSON or another JSON library in Java?

I can serialize a List in my servlet on GAE, but I can't deserialize it. What am I doing wrong?

This is my class Video in GAE, which is serialized:


package legiontube;

import java.util.Date;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Video {

@PrimaryKey
private String id;

@Persistent
private String titulo;

@Persistent
private String descricao;

@Persistent
private Date date;

/**
* @param id
* @param titulo
* @param descricao
* @param date
*/

public Video(){};

public Video(String id, String titulo, String descricao, Date date) {
//super();
this.id = id;
this.titulo = titulo;
this.descricao = descricao;
this.date = date;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getTitulo() {
return titulo;
}

public void setTitulo(String titulo) {
this.titulo = titulo;
}

public String getDescricao() {
return descricao;
}

public void setDescricao(String descricao) {
this.descricao = descricao;
}

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}

}


This is my class Video in my other application, where I try to deserialize:


package classes;

import java.util.Date;

public class Video {
private String id;
private String titulo;
private String descricao;
private Date date;

/**
* @param id
* @param titulo
* @param descricao
* @param date
*/
public Video(String id, String titulo, String descricao, Date date) {
//super();
this.id = id;
this.titulo = titulo;
this.descricao = descricao;
this.date = date;
}

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}

}

Answer

With Gson, you'd just need to do something like:

List<Video> videos = gson.fromJson(json, new TypeToken<List<Video>>(){}.getType());

You might also need to provide a no-arg constructor on the Video class you're deserializing to. What's the specific issue you're having with deserializing?