Java Jersey MongoDB GET子列表

时间:2017-06-29 05:02:33

标签: java mongodb api jersey

我正在开发一个API来获取BSON中的位置列表,如下所示。

{
"_id" : ObjectId("59512a4ca33bc80248fb1435"),
"id" : NumberLong(1),
"locationId" : NumberLong(17),
"position" : [ 
    {
        "latitude" : 12342.0,
        "longitude" : 1232342.0,
        "time" : "on May 04 09:51:52 CDT 2009"
    }, 
    {
        "latitude" : 12342.0,
        "longitude" : 1232342.0,
        "time" : "on May 04 09:51:52 CDT 2009"
    }
    ]
}

在我的Employee类中,我有一个名为setPosition(List<Position> positions)的方法有没有办法通过使用`emp.get(&#34; position&#34;)<从BSON获取位置数组来将列表传递给此函数? / p>

以下是getAllEmployees()功能,我无法通过将BSOn转换为列表来设置位置

public List<Employee> getAllEmployees() {
    DBObject query = new BasicDBObject();
    DBCursor cursor = employeeCollection.find(query);
    System.out.println("cursor.count : " + cursor.count());
    List<Employee> list = new ArrayList<Employee>();
    while (cursor.hasNext()) { 
             DBObject emp = cursor.next();
             Employee employee = new Employee();
             employee.setId((long) emp.get("id"));
             employee.setLocationId((long) emp.get("locationId"));
             DBObject pos = (DBObject) emp.get("position");
             System.out.println("pos : " +pos);
             List<Position> positions = *HERE COMES THE PROBLEM!!!!!*
             employee.setPosition(positions);
             list.add(employee);
    }
    return list;
}

如何将位置数组从mongodb直接传递给setPosition函数?

1 个答案:

答案 0 :(得分:0)

最后,我得到了这个工作。以下是getAllEmployees()函数。解决方案是使用BasicDBList代替BDObject

public List<Employee> getAllEmployees() {
    DBObject query = new BasicDBObject();
    DBCursor cursor = employeeCollection.find(query);
    System.out.println("cursor.count : " + cursor.count());
    List<Employee> list = new ArrayList<Employee>();
    while (cursor.hasNext()) { 
             DBObject emp = cursor.next();
             Employee employee = new Employee();
             employee.setId((long) emp.get("id"));
             employee.setLocationId((long) emp.get("locationId"));
             BasicDBList positions = (BasicDBList) emp.get("position");
             for (Object position : positions) {
                Position pos = new Position();
                pos.setLatitude((double) ((DBObject) position).get("latitude"));
                pos.setLongitude((double) ((DBObject) position).get("longitude"));
                pos.setTime((String) ((DBObject) position).get("time"));
                employee.getPosition().add(pos);
            }
             list.add(employee);
    }
    return list;
}