gpt4 book ai didi

java - (Gson) JSON 到包含 ArrayList 的 Java 对象

转载 作者:行者123 更新时间:2023-11-30 04:09:53 28 4
gpt4 key购买 nike

我正在从 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
}

Verbete 的转换to 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

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

最佳答案

这样做

    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);

关于java - (Gson) JSON 到包含 ArrayList<Class> 的 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19891422/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com