使用BasicDBObject从JSON字符串的列表中获取键和值

时间:2022-01-19 19:32:42

I have a String with a JSON that contains a list. Its something like this:

我有一个包含列表的JSON字符串。它是这样的:

{
    "counts":[
        {"foo827138": 123124, "bar2918":312312, "something_else321-313":2321321},
        {"foo1231412": 4321, "bar1231515":123, "something_else3012931":7282},
        {"foo1210820": 1234, "bar10293810":3112, "something_else12094":1321}
    ]
}

After parsing it with BasicDBObject.parse():

解析后,使用BasicDBObject.parse():

DBObject doc = BasicDBObject.parse(jsonString);  

How can I get the keys and values on counts list?

如何获取计数列表中的键和值?

PS.: doc.get("counts") returns a BasicDBList object. I can only iterate over this with:

get(“计数”)返回一个BasicDBList对象。我只能用:

for (Object a : doc) {
    // Something
}

Object does not provide a get() method or something like. So I don't know how to get any of my key names and respective values.

对象不提供get()方法或类似的东西。所以我不知道如何得到键名和各自的值。

2 个解决方案

#1


1  

Document document = Document.parse(jsonString);
List<Document> countsArray = document.get("counts",List.class);
for (Document doc : countsArray){
    doc.keySet(); //keys
    doc.values(); //values
    for (Map.Entry entry : doc.entrySet()){
        // iterate over each pair
    }
}

#2


0  

Have you tried yourObject.get("keyname")

你有试过yourObject.get(“keyname”)

#1


1  

Document document = Document.parse(jsonString);
List<Document> countsArray = document.get("counts",List.class);
for (Document doc : countsArray){
    doc.keySet(); //keys
    doc.values(); //values
    for (Map.Entry entry : doc.entrySet()){
        // iterate over each pair
    }
}

#2


0  

Have you tried yourObject.get("keyname")

你有试过yourObject.get(“keyname”)