我想使用 RecyclerView
在新闻提要中显示不同类型的故事.例如,一个故事可以有一个天气如何变化的模板。因此 JSON 数据将包含日期、温度等。
我从数据库中以 JSON 格式下载故事并解析它们。目前,我将解析后的 JSON 对象存储在 List<FeedStoryContainer>
中。 .
FeedStoryContainer
有两个属性,一个 int
代表类型和 Object
包含数据。当需要绑定(bind)数据时,我转换 Object
进入基于int
的正确故事类型类型。这种做法可以吗?
最佳答案
在我看来,您的故事类型最好具有相同的基础和 API。使用相同的 api 将它们保存在 List< StoryBase > 中。根据类型 ( int ) 转换对象是一些解决方案,但迟早会无济于事。更好的是使用多态性。
class Story
{
void apply( Viewer viewer )
{
System.out.println( "Default implementation" )
}
}
class News extends Story
{
void apply( Viewer viewer )
{
viewer.setTextBody( this.title + " " + this.content );
}
}
class Wheather extends Story
{
void apply( Viewer viewer )
{
viewer.setTextBody( this.title + " " + this.temperature );
}
}
code
List< Story > list;
for( Story story : list )
{
story.apply( this );
}
关于java - 如何在列表中存储不同类型的 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31158337/