Convert dbcursor object into json

99封情书 提交于 2019-12-24 00:19:11

问题


I have a java application where I want to send json data fro servlet to a jsp. I am using mongodb as a database and Gson library for Json.

I am new to Java & Mongo.

Here is the code for querying the database:

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

And this is the result after querying the database

{ "_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"]}

What I want to achieve is to convert the above result into a JSON and access the JSON using fields such as 'Incident Date', 'Status' by parsing the result as json. I tried to parse the original result as json but I think it doesn't work like that

Here is what I have tried. 1. Converted the 'cursor' to ArrayList

    List<DBObject> myList = new ArrayList<DBObject>();
    myList = cursor.toArray();
  1. Tried to convert the ArrayList into the JSON

    JSON json =new JSON();
    String serialize = json.serialize(cursor);
    

I tried the following code, but I am getting this error

    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)

Can anyone please help me?


回答1:


Iterate over cursor and push data into JSONObject and then put jsonObject into jsonarray like this :

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



回答2:


Rename your second key "Incident Date" to "Incident_Date". Usually json key names are with lower cases but nevermind. After that if you want to use Gson to have your json object parsed into an object the smooth but harder way is to create a java object similar to your json object. Something like that:

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

And your _id part of the json:

public class _id {

    private String $oid;

    public String get$oid() {
        return this.$oid;
    }

    public void set$oid(String $oid) {
        this.$oid = $oid;
    }
}

If you have your json into a string for example you can use Gson to parse it and get an instance ot MyJSONObject like that:

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

Done - myJSONObject is now filled with your json object.



来源:https://stackoverflow.com/questions/29986378/convert-dbcursor-object-into-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!