title: Converting BSON Type ObjectId to JSON (Storing in Mongodb) -Java
body: <p>new Gson().toJson(new ObjectId())</p>
  
  <p>When I do the above, the output I get is  </p>
  
  <blockquote>
    <p>"_id" : { "_time" : 1374347520 , "_machine" : -1025067326 , "_inc" : 585905201 , "_new" : false} </p>
  </blockquote>
  
  <p>But Actually I want it to be as </p>
  
  <blockquote>
    <p>"_id":{"$oid":51eae100c2e6b6c222ec3431}</p>
  </blockquote>
  
  <p>which is the usual mongodb ID format. What is the preferable method in Java for this?</p>
  
  <p>Update:</p>
  
  <p>My value object</p>
  
  <pre><code>import com.google.gson.annotations.SerializedName;
  import org.bson.types.ObjectId;
  
  public class TaskObject {
  
      @SerializedName("_id")
      private ObjectId _id;
  
      @SerializedName("revNo")
      private int revNo;
  }
  </code></pre>
  
  <p>I am trying to store this to mongodb with a custom _id</p>
  
  <pre><code>TaskObject taskObject = new TaskObject();
  taskObject.set_id(new ObjectId());
  TaskMongoDBClient.getInstance().
          persistNewTaskData(new Gson().toJson(taskObject));
  </code></pre>
  
  <p>What is stored in the mongodb looks like this.</p>
  
  <blockquote>
    <p>_id: { "_time" : 1397464341 , "_machine" : 1441187434 , "_inc" : -1687457948 , "_new" : true}</p>
  </blockquote>
  
  <p>Instead of _id:{"$oid": xxxx} which i can query by using a the oid value.</p>
  
  <p>What I am doing wrong here? please help.</p>
  
  <p>Thanks</p>