我自己也遇到过类似的“问题”,最终将Jackson 与POJO databinding 和Morphia 一起使用。
虽然这听起来有点像用大锤敲碎坚果,但实际上它非常易于使用、功能强大且性能非常好,并且易于维护代码。
小警告:如果您想重用它,您需要将 test_id 字段映射到 MongoDB 的 _id。
第 1 步:创建一个带注释的 bean
您需要提示 Jackson 如何将数据从 JSON 文件映射到 POJO。为了便于阅读,我稍微缩短了课程:
@JsonRootName(value="person")
@Entity
public class Person {
@JsonProperty(value="test_id")
@Id
Integer id;
String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
至于嵌入文档Job,请查看链接的POJO数据绑定示例。
第 2 步:映射 POJO 并创建数据存储
在应用程序初始化期间的某个地方,您需要映射带注释的 POJO。既然你应该已经有一个 MongoClient,我将重用它;)
Morphia morphia = new Morphia();
morphia.map(Person.class);
/* You can reuse this datastore */
Datastore datastore = morphia.createDatastore(mongoClient, "myDatabase");
/*
* Jackson's ObjectMapper, which is reusable, too,
* does all the magic.
*/
ObjectMapper mapper = new ObjectMapper();
实际导入
现在导入给定的 JSON 文件变得如此简单
public Boolean importJson(Datastore ds, ObjectMapper mapper, String filename) {
try {
JsonParser parser = new JsonFactory().createParser(new FileReader(filename));
Iterator<Person> it = mapper.readValues(parser, Person.class);
while(it.hasNext()) {
ds.save(it.next());
}
return Boolean.TRUE;
} catch (JsonParseException e) {
/* Json was invalid, deal with it here */
} catch (JsonMappingException e) {
/* Jackson was not able to map
* the JSON values to the bean properties,
* possibly because of
* insufficient mapping information.
*/
} catch (IOException e) {
/* Most likely, the file was not readable
* Should be rather thrown, but was
* cought for the sake of showing what can happen
*/
}
return Boolean.FALSE;
}
通过一些重构,这可以在通用导入器中转换为 Jackson 注释 bean。
显然,我遗漏了一些特殊情况,但这超出了此答案的范围。