【问题标题】:Convert dbcursor object into json将 dbcursor 对象转换为 json
【发布时间】:2015-05-01 11:54:51
【问题描述】:

我有一个 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();
  1. 尝试将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)

谁能帮帮我?

【问题讨论】:

    标签: java json mongodb gson


    【解决方案1】:

    遍历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;
    }
    

    【讨论】:

    • 我也在尝试使用 org.json 库解析 json,下面是代码 JSONObject obj = new JSONObject(jsonarray); System.out.println(json.getString("状态"));
    • 但我收到此错误 JSONObject["Status"] not found。你能帮忙吗?
    • @Parag 看起来像一些拼写错误,将 System.out.println(json.getString("Status")); 替换为 System.out.println(obj.getString("Status"));
    • @Parag 我不明白你为什么将jsonarray 再次放入jsonobject 并找到key。更多 check this 和我个人推荐 java mongo tutorial 这个家伙用 java 很好地解释了 mongo 可能会对你有所帮助。
    • @Parag 你不能直接这样做JSONObject obj = new JSONObject(jsonarray) 和访问obj.getString("Status")) 你可以这样做jsonarray.getJSONObject(0).getString("Status")); 或for(int i = 0 ; i &lt; jsonarray.length() ; i++){ System.out.println(jsonarray.getJSONObject(i).getString("Status")); } 之类的事情
    【解决方案2】:

    将您的第二个键“事件日期”重命名为“事件日期”。通常 json 键名是小写的,但没关系。 之后,如果您想使用 Gson 将您的 json 对象解析为一个对象,那么平滑但更难的方法是创建一个类似于您的 json 对象的 java 对象。类似的东西:

    public class MyJSONObject {
    
        private String Address;
        private String Incident_Date;
        private String Latitude;
        private String Longitude;
        private List Name;
        private String Status;
        private _id _id;
    
        public String getAddress() {
            return this.Address;
        }
    
        public void setAddress(String address) {
            this.Address = address;
        }
    
        public String getIncident_Date() {
            return this.Incident_Date;
        }
    
        public void setIncident_Date(String incident_date) {
            this.Incident_Date = incident_date;
        }
    
        public String getLatitude() {
            return this.Latitude;
        }
    
        public void setLatitude(String latitude) {
            this.Latitude = latitude;
        }
    
        public String getLongitude() {
            return this.Longitude;
        }
    
        public void setLongitude(String longitude) {
            this.Longitude = longitude;
        }
    
        public List getName() {
            return this.Name;
        }
    
        public void setName(List name) {
            this.Name = name;
        }
    
        public String getStatus() {
            return this.Status;
        }
    
        public void setStatus(String status) {
            this.Status = status;
        }
    
        public _id get_id() {
            return this._id;
        }
    
        public void set_id(_id _id) {
            this._id = _id;
        }
    }
    

    还有你的 _id 部分:

    public class _id {
    
        private String $oid;
    
        public String get$oid() {
            return this.$oid;
        }
    
        public void set$oid(String $oid) {
            this.$oid = $oid;
        }
    }
    

    例如,如果您将 json 转换为字符串,则可以使用 Gson 对其进行解析并获取 MyJSONObject 的实例:

    String jsonString = "{ \"_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\"]}";
    
            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson gson = gsonBuilder.create();
            MyJSONObject myJSONObject = gson.fromJson(jsonString, MyJSONObject.class);
    

    完成 - myJSONObject 现在填充了您的 json 对象。

    【讨论】:

    • 但是 MongoDb 游标对象的格式与 jsonString 不同。
    【解决方案3】:

    您正在做的是,您正在尝试将您的 JsonArray 解析为 Jsonobject(您收到错误的行)。 如果您序列化游标并对其进行解析,那么它将直接返回 jsonArray 而不是 jsonObject。取而代之的是,您可以简单地遍历光标并将其添加到 jsonArray 中(请参阅下面的代码 sn-p )

    `

    FindIterable<Document> findIterable = collection.find(struct.searchQueryObject);
    MongoCursor<Document> cur = findIterable.cursor();  
    JsonArray responses = new JsonArray();
    while(cur.hasNext()) {
        Document doc = cur.next();
        responses.add(doc.toJson());
    }
    

    `

    或者您可以简单地将 getAsJsonObject() 更改为 getAsJsonArray() (但请确保 JsonElement 不为空。)(请参阅下面的代码 sn-p )。

    JSON json =new JSON();
    String serialize = json.serialize(cursor);//make sure string is not empty or null
    JsonElement jelement = new JsonParser().parse(serialize);
    System.out.println(jelement);
    JsonArray  jArray = jelement.getAsJsonArray();
    System.out.println(jArray);
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-06-16
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      相关资源
      最近更新 更多