将dbcursor对象转换为json

时间:2015-05-01 11:54:51

标签: java json mongodb gson

我有一个java应用程序,我想将servlet的json数据发送到jsp。我使用mongodb作为数据库和Json的Gson库。

我是Java&蒙戈。

以下是查询数据库的代码:

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.转换'光标'到ArrayList

    List<DBObject> myList = new ArrayList<DBObject>();
    myList = cursor.toArray();
  1. 尝试将ArrayList转换为JSON

    JSON json =new JSON();
    String serialize = json.serialize(cursor);
    
  2. 我尝试了以下代码,但是我收到了此错误

        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)
    

    有人可以帮助我吗?

3 个答案:

答案 0 :(得分:4)

迭代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;
}

答案 1 :(得分:1)

重命名您的第二个密钥&#34;事件日期&#34;至&#34; Incident_Date&#34;。通常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;
    }
}

你在json的_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对象。

答案 2 :(得分:1)

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

`

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());
}

`

或者您可以简单地使用getAsJsonArray()更改getAsJsonObject()(但请确保JsonElement不为null。)(请参阅下面的代码片段)。

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);

我希望这会有所帮助。