Details
-
New Feature
-
Resolution: Done
-
Major - P3
-
1.0.0-beta2
-
None
-
None
Description
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.
<?php
|
|
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"); |
|
var_dump(json_encode($p)); |
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" } } |
Attachments
Issue Links
- is depended on by
-
PHPLIB-185 BSONDocument and BSONArray should implement JsonSerializable
-
- Closed
-
- is related to
-
CDRIVER-1335 libbson does not properly serialize the Code type to JSON
-
- Closed
-
-
PHPC-49 Create PHP interface for BSON serialization
-
- Closed
-
-
PHPC-410 BSON\fromPHP() handling of non-stdClass objects and unsupported BSON\Type instances
-
- Closed
-
- related to
-
PHPC-561 MongoDB\BSON\ObjectID should be encoded correctly by json_encode
-
- Closed
-
-
PHPC-718 Define extension dependencies
-
- Closed
-
-
PHPC-828 Use canonical extended JSON for Timestamp::jsonSerialize()
-
- Closed
-
- links to