我有一个如下所示的集合:
db.testdata.save(
{
"Indicator": "One",
"secs": [
{
"when": "2013-03-16",
"num": 16,
"choices": [
{
"size": "10",
"mult": "10"
},
{
"size": "10",
"mult": "10"
}
]
},
{
"when": "2013-03-22",
"num": 24,
"choices": [
{
"size": "100",
"mult": "100"
},
{
"size": "100",
"mult": "100"
}
]
}
]
})
我正在尝试使用自定义对象检索它,如下所示:
public class Test {
public static void main(String args[]) throws UnknownHostException {
Mongo mongo = new Mongo();
DB db = mongo.getDB("at");
DBCollection testdata = db.getCollection("testdata");
BasicDBObject query = new BasicDBObject();
query.put("Indicator", "One");
CustomChainData ocd = (CustomChainData) testdata.findOne(query);
ocd.getWhen().size();
}
}
import java.util.List;
import com.mongodb.BasicDBObject;
public class CustomChainData extends BasicDBObject{
public CustomChainData() {
super();
}
@SuppressWarnings("unchecked")
public List<WhenData> getWhen() {
return (List<WhenData>) get("secs");
}
public void setWhen(List<WhenData> expirationDts) {
put("secs", expirationDts);
}
}
import com.mongodb.BasicDBObject;
public class WhenData extends BasicDBObject{
public String getSize() {
return (String) get("size");
}
public void setSize(String size) {
put("size", size);
}
}
不幸的是,我不断得到:
线程“主”java.lang.ClassCastException 中的异常:com.mongodb.BasicDBObject 无法在 Test.main 中转换为 com.CustomChainData(Test.java:19)