'How to convert "$oid" mongo object with Gson + Java

I spend long time to achieve conversion an Object like "user" with Google Json lib and a result from Mongodb.

So here an example of conversion of Mongodb result. I hope that it help someone.

{"_id":{"$oid":"6234a4708c9c871cb7f6de6c"},"email":"[email protected]","pwd":"something","roles":{"rolename":"reader","comment":true},"created":"2022-03-18T15:25:36.108841Z"}

To get the oid, we need to create a ObjectIdTypeAdapter



Solution 1:[1]

Create an adapter for "$oid":

package com.energytronik.pojo;

import java.io.IOException;
import org.bson.types.ObjectId;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

public class ObjectIdTypeAdapter extends TypeAdapter<ObjectId> {
    @Override
    public void write(final JsonWriter out, final ObjectId value) throws IOException {
        out.beginObject()
           .name("$oid")
           .value(( null != value ? value.toString() : null) )
           .endObject();
           
    }
}

The oid:

package com.energytronik.pojo;

import com.google.gson.annotations.Expose;

public class Oid {
    @Expose
    public String $oid;
}

The user:

package com.energytronik.pojo;

import com.google.gson.annotations.Expose;

public class User {
    @Expose
    public Oid _id;
    @Expose
    public String email;
    @Expose
    public String pwd;
    @Expose
    public Role roles;
    @Expose
    public String created;
}

Call Mongo with a payload:

{"email":"[email protected]","pwd":"something"}

The document.first().toJson() response is:

{"_id":{"$oid":"6234a4708c9c871cb7f6de6c"},
   "email":"[email protected]","pwd":"something",
   "roles":{"rolename":"reader","comment":true},
   "created":"2022-03-18T15:25:36.108841Z"}

Now, parse to User object

public class YourClass{
   static Gson gson = new GsonBuilder().
         excludeFieldsWithoutExposeAnnotation().
         registerTypeAdapter(ObjectId.class, new ObjectIdTypeAdapter()).
         create();

   public static void main(String[] args) {
    User u = new User();
        u.email = "[email protected]";
        u.pwd = "something";
    String q = gson.toJson(u);
    // .... CALL MONGO DB and parse the returned document toJson()
    Document d = YourDb.call("users", q);
    
    User nu = gson.fromJson(d.toJson(), User.class);
    System.out.println("object id:" + nu._id.$oid  + "\n" + gson.toJson( nu ) );
   }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bruno Poultier