1

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

我的代码基本上是:

动词

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
}

名词动词

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

意义动词

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

类别Verbete

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

从到 JSON 的转换Verbete给了我这个字符串(这似乎是正确的,对吧?):

{"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

有人可以给我一种方法来进行这种转换吗?谢谢你。

4

1 回答 1

1

这样做

    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);
于 2013-11-10T16:19:45.433 回答