1

我需要从以下 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"
                }
            ]
        }
    ] }

代码:

DBCollection 集合 = 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(); 地图 = obj.toMap();

      for (Map.Entry<DBObject, DBObject> entry : map.entrySet()) {
          System.out.println("Key : " + entry.getKey() + " Value : "
                  + entry.getValue());


      }
              }

结果:

键:_id 值:523f910681a9535f8af5aa91

键:ThirdOne 值:[{ "explicitElements" : [{"name":"mytag", "value":"myrequest"},{"name":"booleantest", "value":"true"}]}]

我只想得到

键:“名称” 值:“mytag”

键:“值”值:“我的请求”等...

有关如何使用 DBObjects 执行此操作的任何建议?

4

1 回答 1

0

你这里有一堆存储在 s 中的值字段,存储在DBObjects 中,DBList存储在 s 中,存储在s 中,存储DBObject在s 中,由 a 迭代。由于这种复杂的文档结构,当您只想输出特定叶子上的内容时,您需要遍历整个树。DBListDBObjectDBCursor

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());
           }
     }
}
于 2013-09-12T08:30:59.147 回答