现在,我正在将电影作为课程存储。它具有标题,导演等内容。我首先将其存储在哈希图中,然后使用ObjectMapper
将其写入本地json文件。现在,我想在读取该文件后将其加载到哈希图中。在这里,我将movies
作为<Integer, Object>
的哈希图
ObjectMapper objectMapper = new ObjectMapper();
try(InputStream fileStream = new FileInputStream("../test/data.json")) {
Movie movie = objectMapper.readValue(fileStream, Movie.class);
int curr = movie.getId();
Integer idx = new Integer(curr);
movies.put(idx, movie);
}
我想知道,是否需要实例化我的类Movie
并从json文件中传递属性,然后再将其添加到哈希图中?还是有更简单的方法?
这是我的Movie
类的主要部分。还有一些未在此处列出的吸气剂和吸气剂。
public class Movie {
private int id;
private String title;
private String director;
public Movie(int id, String title, String director) {
this.id = id;
this.title = title;
this.director = director;
}
}
当我将哈希图另存为json时,将是一个示例
{"1":{"id":1,"title":"hormesis","director":"bruv"},"2":{"id":2,"title":"asdf","director":"bean"}}
因此,从本质上讲,我有一个计数器作为索引,每次将电影添加到哈希图中时,计数器都会增加。我实例化每个电影类并将属性传递给构造函数,然后再将其添加到以索引为键的哈希图中。完成后,我使用ObjectMapper编写json文件,其中movies
是哈希图的名称
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("../test/data.json"), movies);
当我再次启动程序时,我希望将data.json加载到哈希图中。 我试图读取这样的文件
ObjectMapper mapper = new ObjectMapper();
File from = new File("../test/data.json");
TypeReference<HashMap<Integer,Object>> typeRef = new
TypeReference<HashMap<Integer,Object>>() {};
HashMap<Integer, Object> o = mapper.readValue(from, typeRef);
我尝试以Movie
对象的形式检索哈希图中的第一项
HashMap<Integer, Object> o = mapper.readValue(from, typeRef);
Movie test = (Movie)o.get(1);
System.out.println("Got " + test.getTitle());
但是,这会导致出现错误
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.company.Movie