我需要从下面的json获得所有名称字段的列表。我试图通过映射一个DBObject来实现这一点。
杰森:
{
"firstOne": [
{
"file": "FileA",
"Data": "One",
"version": "0.4"
}
],
"secondOne": [
{
"elementName": "version",
"complexElement": "true",
"elementDataType": ""
}
],
"ThirdOne": [
{
"elementName": "version",
"explicitElements": [
{
"name": "mytag",
"type": "String",
"value": "myrequest"
},
{
"name": "booleantest",
"type": "Boolean",
"value": "true"
}
]
}
] }代码:
DBCollection collection = mongoTemplate.getCollection("testTag"); Map map =新HashMap();DBObject obj =null;BasicDBObject查询=新BasicDBObject();query.put("ThirdOne.explicitElements.name","myTag");BasicDBObject字段=新BasicDBObject();fields.put("ThirdOne.explicitElements.name",1);fields.put("ThirdOne.explicitElements.value",1);DBCursor cursor2 =DBCursor(查询,字段);while (cursor2.hasNext()) { obj = cursor2.next();map = obj.toMap(); 对于(Map.Entry条目: map.entrySet()) { System.out.println("Key:“+ entry.getKey() +”值:“+ entry.getValue());}
结果:
键:_id值:523f910681a9535f8af5a91 键: ThirdOne值:[{ "explicitElements“:{”explicitElements“:{”explicitElements“:”mytag“,"value":"myrequest"},{”explicitElements“:”booleantest“,”explicitElements“:”true“}}]
我只想
键:"name“值:"mytag” 键:“值”值:“我的请求”等等。
对于如何使用DBObjects实现这一点,有什么建议吗?
发布于 2013-09-12 08:30:59
这里有一组值字段,存储在DBObject中,存储在DBList中,存储在DBObject中,存储在DBList中,存储在由DBCursor迭代的DBObjects中。由于这个复杂的文档结构,当您只想输出特定叶子上的文档时,您需要遍历整棵树。
while (cursor2.hasNext()) {
// you are now iterating a list objects with three Fields:
// FirstOne, SecondOne and ThirdOne. You only want ThirdOne
obj = cursor2.next();
map = obj.toMap();
DBList thirdOne = (DBList)map.get("ThirdOne");
// now we iterat the list in ThirdOne
for (Object o: thirdOne) {
DBObject thirdOneEntry = (DBObject)o;
// we get the explicitElements-array from each entry
DBList explicitElements = (DBList)thirdOneEntry.get("explicitElements");
// now we iterate the expliciteElements
for (Object o: explicitElements) {
DBObject explicitElementsEntry = (DBObject)o;
// and write them
Object key = explicitElementsEntry.get("key");
Object value = explicitElementsEntry.get("value");
System.out.println("Key : " + key.toString() + " Value : " value.toString());
}
}
}https://stackoverflow.com/questions/18756057
复制相似问题