Java 如何访问对象内部对象的属性?
我有一个像这样的物体:Java 如何访问对象内部对象的属性?,java,mongodb,object,gson,Java,Mongodb,Object,Gson,我有一个像这样的物体: public class Pelicula { private String popularity; private Object belongs_to_collection; public Pelicula() { this.popularity = popularity; } public String getPopularity() { return popularity; }
public class Pelicula {
private String popularity;
private Object belongs_to_collection;
public Pelicula() {
this.popularity = popularity;
}
public String getPopularity() {
return popularity;
}
public Object getBelongs_to_collection() {
return belongs_to_collection;
}
}
此对象是使用Gson将mongodb文档转换为对象Pelicula,该对象包含一些字符串,并且一个对象属于\u集合
{
"adult": false,
"backdrop_path": "/8SqBiesvo1rh9P1hbJTmnVum6jv.jpg",
"belongs_to_collection": {
"id": 304378,
"name": "Independence Day - Colección",
"poster_path": "/diCxphvzqas0Tr5eq7tLUzg5M7d.jpg",
"backdrop_path": "/p7oqa94XgNGVMazXwR49QfyGgtx.jpg"
},
"budget": 165000000
...
对于创建对象,我使用此函数:
public List getAllMovies() {
List<Pelicula> allMovies = new ArrayList();
Pelicula movie;
for (Document p : getCollection().find()) {
movie = getGson().fromJson(p.toJson(), Pelicula.class);
allMovies.add(movie);
}
System.out.println(allMovies.get(0).getPopularity());
return allMovies;
}
公共列表getAllMovies(){
List allMovies=new ArrayList();
Pelicula电影;
对于(文档p:getCollection().find()){
movie=getGson().fromJson(p.toJson(),Pelicula.class);
添加(电影);
}
System.out.println(allMovies.get(0.getPopularity());
归还所有电影;
}
正如你所看到的,我可以打印财产的流行程度。此外,我还可以使用toString打印属于对象Pelicula的对象集合
问题是:我是否可以在不创建继承Pelicula的对象Bowns to集合的情况下逐个访问Bowns to集合的属性?附带问题:Pelicula对象将如何实例化,当私有属性不存在setter时?@reporter GSON使用反射来填充值。您可以创建
TypeAdapter
或创建所属集合
的表示。这就是GSON(谷歌)的魔力。Pelicula电影;对于(Document p:getCollection().find()){movie=getGson().fromJson(p.toJson(),Pelicula.class);allMovies.add(movie);}创建Pelicula电影对象时,Gson将mongoDB文档转换为Pelicula对象。@kalsowerus您能举一个TypeAdapter的例子吗?我不知道是什么。