我需要从以下json获取所有名称字段的列表。我试图通过映射DBObject来做到这一点。
JSON:
{
"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"
}
]
}
] }
CODE:
DBCollection collection = mongoTemplate.getCollection(“testTag”);
Map<DBObject, DBObject> map = new HashMap<DBObject, DBObject>(); DBObject obj =null; BasicDBObject query = new BasicDBObject(); query.put("ThirdOne.explicitElements.name", "myTag"); BasicDBObject fields = new BasicDBObject(); fields.put("ThirdOne.explicitElements.name", 1); fields.put("ThirdOne.explicitElements.value", 1); DBCursor cursor2 = collection.find(query, fields); while
(cursor2.hasNext()){obj = cursor2.next(); map = obj.toMap();
for (Map.Entry<DBObject, DBObject> entry : map.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); } }
结果:
键:_id值:523f910681a9535f8af5aa91
Key:ThirdOne Value:[{“explicitElements”:[{“name”:“mytag”, “value”:“myrequest”},{“name”:“booleantest”,“value”:“true”}]}]
我想只获得
key:“name”value:“mytag”
key:“value”value:“myrequest”等......
有关如何使用DBObjects执行此操作的任何建议吗?
答案 0 :(得分:0)
这里有一堆存储在DBObject
存储在DBList
存储在DBObject
中的DBList
的值字段,存储在DBObject
存储在DBCursor
中的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());
}
}
}
存储在{{1}}中1}}由{{1}}迭代。由于这种复杂的文档结构,当您只想输出特定叶子上的那些时,您需要遍历整个树。
{{1}}