(Gson)JSON到包含ArrayList <class> </class>的Java对象

时间:2013-11-10 15:19:49

标签: java json arraylist deserialization gson

我正在从Web服务中检索数据,该服务返回一个带有我对象的JSON表示的String。除了其他简单属性之外,我的对象还有两个ArrayList<>个其他对象。这似乎是Gson的一个问题。我一直在寻找,答案与我的具体问题不符。

我的代码基本上是:

Verbete

public class Verbete implements Serializable{
    private long id;
    private List<NomesVerbete> nomes;
    private List<SignificadosVerbete> significados;
    private int totalAcessos = 0;
    private Date dataLancamento;
    private int relevancia = 0;
    //getters and setters
}

NomesVerbete

public class NomesVerbete implements Serializable {
    private long id;
    private String nome;
    private String etimologia;
    //getters and setters
}

SignificadosVerbete

public class SignificadosVerbete implements Serializable{
    private long id;
    private String significado;
    private CategoriaVerbete categoria;
    //getters and setters
}

CategoriaVerbete

public class CategoriaVerbete implements Serializable{
    private long id;
    private String nome;
    private String descricao;
    private int serie;
    //getters and setters
}

Verbete到JSON的转换为我提供了这个字符串(看起来是正确的,对吧?):

{"id":81,"nomes":[{"id":124,"nome":"aleluia","etimologia":"asasiajisjaijs"},{"id":126,"nome":"amém","etimologia":"asasiajisjaijs"}],"significados":[{"id":67,"significado":"asasjaijsiajsoijaoisjaoisj","categoria":{"id":3,"nome":"Nada","descricao":"asuahushaus","serie":1}}],"totalAcessos":0,"dataLancamento":1382066568000,"relevancia":0}

但是,当我尝试将此JSON字符串转换为Verbete时,它不起作用,受到我在尝试访问对象时获得的NullPointerException的影响。这是我从Json的转换:

Gson gson = new GsonBuilder().create();
Verbete verbete = gson.fromJson(resposta[1], Verbete.class); //resposta[1] is the json string above

有人可以给我一个方法进行转换吗? 谢谢。

1 个答案:

答案 0 :(得分:2)

喜欢这个

    final String json = "{\"id\":81,\"nomes\":[{\"id\":124,\"nome\":\"aleluia\",\"etimologia\":\"asasiajisjaijs\"},{\"id\":126,\"nome\":\"amém\",\"etimologia\":\"asasiajisjaijs\"}],\"significados\":[{\"id\":67,\"significado\":\"asasjaijsiajsoijaoisjaoisj\",\"categoria\":{\"id\":3,\"nome\":\"Nada\",\"descricao\":\"asuahushaus\",\"serie\":1}}],\"totalAcessos\":0,\"dataLancamento\":1382066568000,\"relevancia\":0}";
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class,
            new JsonDeserializer<Date>() {
                @Override
                public Date deserialize(JsonElement jsonElement, Type type,
                        JsonDeserializationContext context)
                        throws JsonParseException {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(jsonElement.getAsLong());
                    return calendar.getTime();
                }
            });
    Gson gson = gsonBuilder.create();
    Verbete verbete = gson.fromJson(json, Verbete.class);

    System.out.println(verbete);