mongodb转实体对像,从MongoDB检索值时将DBObject转换为Java对象

From my Java application, I have stored the values in mongoDB in ArrayList(set of Java objects).

How can I retrieve the data from DBObject

I am storing the data in mongoDB like this:

{ "students" : [{"firstName" : "Jesse", "lastName" : "Varnell", "age" : "15", "gender" : "M" }, { "firstName" : "John", "lastName" : "Doe", "age" : "13", "gender" : "F"}] }

I am having the Java Object for the Student like:

public class Student {

public String firstName;

public String lastName;

public String age;

public String gender; // M, F

}

I am retrieving the data from mongoDB like:

BasicDBObject query = new BasicDBObject();

query.put("user", username);

DBCursor cursor = theCollection.find(query);

while (cursor.hasNext()) {

DBObject theObj = cursor.next();

//How to get the DBObject value to ArrayList of Java Object?

}

解决方案

You can do it as follows :

List students = new ArrayList();

BasicDBObject query = new BasicDBObject();

query.put("user", username);

DBCursor cursor = theCollection.find(query);

while (cursor.hasNext()) {

DBObject theObj = cursor.next();

//How to get the DBObject value to ArrayList of Java Object?

BasicDBList studentsList = (BasicDBList) theObj.get("students");

for (int i = 0; i < studentsList.size(); i++) {

BasicDBObject studentObj = (BasicDBObject) studentsList.get(i);

String firstName = studentObj.getString("firstName");

String lastName = studentObj.getString("lastName");

String age = studentObj.getString("age");

String gender = studentObj.getString("gender");

Student student = new Student();

student.setFirstName(firstName);

student.setLastName(lastName);

student.setAge(age);

student.setGender(gender);

students.add(student);

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值