user648026 user648026 - 1 year ago 104
JSON Question

transpose DBObject to json

I have a list of mongo db objects List from mongo fetch

for example the DBObject contains column name and order:

student name,1
student id,2
student address,3

I would like to transpose this data for datatables ui to json like so:

        { title: "student name" },
{ title: "student id" },
{ title: "student address" }

I looked up GSON lib but it seems like i need to add annotations to my objects - no intentions of doing so.

Answer Source

Suppose you have your Pojo like this:

class YourPojo {
    private String title;
    public String getTitle() {
        return title;
    public void setTitle(String title) {
        this.title = title;

You can build Gson json:

final JsonArray datasets = new JsonArray();
for (String key: dbObject.keySet()) {
    JsonObject dataset = new JsonObject();
    dataset.addProperty("title", key);

And then convert it to your pojo:

Type listType = new TypeToken<ArrayList<YourPojo>>(){}.getType();
List<YourPojo> yourPojoList = new Gson().fromJson(datasets, listType);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download