我有一个 java 应用程序,我想在其中将 json 数据从 servlet 发送到 jsp。我使用 mongodb 作为 Json 的数据库和 Gson 库。
我是 Java 和 Mongo 的新手。
下面是查询数据库的代码:
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB database = mongoClient.getDB("MyTestDatabase");
coll = database.getCollection("players");
BasicDBObject fields = new BasicDBObject();
fields.put("_id", 0);
fields.put("Incident Date", 1);
fields.put("Longitude", 1);
fields.put("Latitude", 1);
fields.put("Address", 1);
fields.put("Status", 1);
fields.put("Name", 1);
doc.put("Address", "Mumbai");
cursor = coll.find(doc,fields);
这是查询数据库后的结果
{ "_id" : { "$oid" : "5540cae37a104f6bbfe7c9f5"} , "Incident Date" : "30/4/2015" , "Longitude" : "77.61528809" , "Latitude" : "12.9245331" , "Address" : "Mumbai" , "Status" : "Ok" , "Name" : [ "1.ABC" , "2.XYZ" , "3.PQR"]}
我想要实现的是将上述结果转换为 JSON,并通过将结果解析为 json,使用“事件日期”、“状态”等字段访问 JSON。我试图将原始结果解析为 json,但我认为它不能像那样工作
这是我试过的。 1. 将 'cursor' 转换为 ArrayList
List<DBObject> myList = new ArrayList<DBObject>();
myList = cursor.toArray();
尝试将 ArrayList 转换为 JSON
JSON json =new JSON(); String serialize = json.serialize(cursor);
我尝试了下面的代码,但是我得到了这个错误
JsonElement jelement = new JsonParser().parse(serialize);
System.out.println(jelement);
JsonObject jobject = jelement.getAsJsonObject();//error at this line
System.out.println(jobject);
Exception in thread "main" java.lang.IllegalStateException: Not a JSON Object: [{"_id":{"$oid":"5540cae37a104f6bbfe7c9f5"},"Incident Date":"30/4/2015","Longitude":"77.61528809","Latitude":"12.9245331","Address":"Mumbai","Status":"Ok","Culprits Name":["1.ABC","2.XYZ","3.PQR"]}]
at com.google.gson.JsonElement.getAsJsonObject(JsonElement.java:90)
谁能帮帮我?
最佳答案
遍历 cursor
并将数据推送到 JSONObject
中,然后将 jsonObject
放入 jsonarray
中,如下所示:
public JSONArray getJsonData() throws JSONException {
JSONArray jsonarray = new JSONArray();
BasicDBObject criteria = new BasicDBObject();
BasicDBObject projections = new BasicDBObject();
criteria.put("Address", "Mumbai");
projections.put("_id", 0);
projections.put("Incident Date", 1);
projections.put("Longitude", 1);
projections.put("Latitude", 1);
projections.put("Address", 1);
projections.put("Status", 1);
projections.put("Name", 1);
DBCursor cursor = coll.find(criteria, projections);
while(cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
jsonobj = new JSONObject();
BasicDBList name = (BasicDBList) obj.get("Name");
jsonobj.put("Incident Date", obj.getString("Incident Date"));
jsonobj.put("Longitude", obj.getString("Longitude"));
jsonobj.put("Latitude", obj.getString("Latitude"));
jsonobj.put("Address", obj.getString("Address"));
jsonobj.put("Status", obj.getString("Status"));
jsonobj.put("Name", name);
jsonarray.put(jsonobj);
}
return jsonarray;
}
关于java - 将 dbcursor 对象转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29986378/