我有以下数据,我正在尝试读取数据并在变量中分配每个数据,但无法获取info
中的数据,仍然给我null
或{{1 }和email
phone
在java代码
下面 {
"_id": ObjectId ( "56c570d904df6c51b463da54"),
"Name": "John Smith"
"Age": 31,
"Info": {
"Email", "john.smith@mail.com"
"Phone", "+987654321"
}
}
答案 0 :(得分:2)
看起来很近!代码中有几个错误:
Null
更改为null
document.getString( "info.email")
将无效。您应该将子文档分配给变量,然后尝试从中获取数据。我还没有测试过,但我认为这样的事情会更好:
findAll.forEach (new Block <Document> () {
@Override
public void apply (Document document) {
String name = document.getString ("name")! = null? document.getString( "name") : "";
int age = document.getInteger ( "age", 0);
// Get the info subdocument
Document info = document.get("info", Document.class);
String email = "";
String phone = "";
if (info != null) {
email = info.getString ("email")! = null? info.getString("email") : "";
phone = info.getString ("phone")! = null? info.getString("phone") : "";
}
Costumer costumer = new Costumer (name, age, email, phone);
System.out.println(costumer);
}
});
希望有所帮助。