我有一个Q.all(promises).then(function (results) {
results.forEach(function(results, i) {
var id = ids[i];
})
});
类,我必须在目录Movie
上以JSON文件的形式存储数据库
电影类有一个管理员将新电影列表添加到数据库的方法。
问题是,在创建第一部电影时,JSON不是Database\Movies.JSON
对象的数组。当我尝试添加后续电影时,我需要从中读取并将其创建为电影对象数组。在Jackson JSON API上有这样一种巧妙的方法吗?
我正在使用最新的Jackson 2.6.3
movies
我已将其创建为电影对象数组。
public void createMovie() {
ObjectMapper objectMapper = new ObjectMapper();
File f = new File("./Database/Movies.json");
if (f.exists() && !f.isDirectory()) { // if existing data exist, read
// from it and append new movie
// data
} else {
try {
objectMapper.writeValue(new FileOutputStream(f), this);
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
但是当我尝试使用以下方法处理现有数据时,它会在第一行崩溃
objectMapper.writeValue(new FileOutputStream(f), Collections.singleton(this));
错误跟踪
List<Movie> myMovies = objectMapper.readValue(f,objectMapper.getTypeFactory().constructCollectionType(List.class, Movie.class));
myMovies.add(this);
objectMapper.writeValue(new FileOutputStream(f), myMovies);
示例JSON数据
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:857)
at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:62)
at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:520)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:258)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:125)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:245)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:217)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:25)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3736)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2658)
at entity.Movie.createMovie(Movie.java:167)
答案 0 :(得分:1)
为避免处理此数组/非数组问题,应始终在文件中存储json数组。您可以将第一部电影添加为包含此单个元素的数组。你可以用:
objectMapper.writeValue(new FileOutputStream(f), Collections.singleton(this));