Uploaded image for project: 'PHP Driver: Extension'
  1. PHP Driver: Extension
  2. PHPC-459

BSON objects should implement JsonSerializable

    • Type: Icon: New Feature New Feature
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 1.2.0
    • Affects Version/s: 1.0.0-beta2
    • Component/s: None
    • Labels:

      Currently we can go from BSON->JSON value, and PHP->BSON->JSON but not PHP->JSON.

      It seems like its not a big deal, needing the intermedied BSON format, but it is bigger deal then I first realized as people want to simply json dump their objects for APIs for example.

      echo json_encode($model);

      When $model contains ObjectID, the ObjectID will be serialized as empty.

      class Person implements JsonSerializable {
          protected $id;
          protected $name;
          function __construct($name) {
              $this->id = new MongoDB\BSON\ObjectID();
              $this->name = (string)$name;
          function JsonSerialize() {
              $arr = array(
                  "name" => $this->name,
                  "id"   => $this->id,
              return $arr;
      $p = new Person ("Jon Jonsson");
      string(30) "{"name":"Jon Jonsson","id":{}}"

      This could have been worked around by allowing BSON\fromPHP() serialization of BSON\Type objects since they always result in a fully qualified json object, e.g.:

      { "$oid" : "56213654bd21b96c3e4e31c1" }

      So the jsonSerialize() function would become:

          function JsonSerialize() {
              $arr = array(
                  "name" => $this->name,
                  "id"   => $this->id,
              $bson = MongoDB\BSON\fromPHP($this->id);
              $json = MongoDB\BSON\toJSON($bson);
              $arr["id"] = $json;
              return $arr;

      and would result in:

      {"name":"Jon Jonsson","id":{ "$oid" : "56213746bd21b9718b1d7371" } }

            jmikola@mongodb.com Jeremy Mikola
            bjori Hannes Magnusson
            1 Vote for this issue
            5 Start watching this issue