Skip to content

Commit 9744704

Browse files
committed
Merge branches 'pr/97' and 'pr/98'
GODRIVER-590 GODRIVER-562 Change-Id: If800aceefac70ad6deb98411a012c32f6a30fa0e
3 parents 16cda52 + 44aa3e6 + 2af8064 commit 9744704

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

bson/objectid/objectid.go

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,11 @@ func FromHex(s string) (ObjectID, error) {
7777
return oid, nil
7878
}
7979

80+
// MarshalJSON returns the ObjectID as a string
81+
func (id ObjectID) MarshalJSON() ([]byte, error) {
82+
return json.Marshal(id.Hex())
83+
}
84+
8085
// UnmarshalJSON populates the byte slice with the ObjectID. If the byte slice is 64 bytes long, it
8186
// will be populated with the hex representation of the ObjectID. If the byte slice is twelve bytes
8287
// long, it will be populated with the BSON representation of the ObjectID. Otherwise, it will
@@ -88,14 +93,25 @@ func (id *ObjectID) UnmarshalJSON(b []byte) error {
8893
copy(id[:], b)
8994
default:
9095
// Extended JSON
91-
m := make(map[string]string)
92-
err := json.Unmarshal(b, &m)
96+
var res interface{}
97+
err := json.Unmarshal(b, &res)
9398
if err != nil {
9499
return err
95100
}
96-
str, ok := m["$oid"]
101+
str, ok := res.(string)
97102
if !ok {
98-
return errors.New("not an extended JSON ObjectID")
103+
m, ok := res.(map[string]interface{})
104+
if !ok {
105+
return errors.New("not an extended JSON ObjectID")
106+
}
107+
oid, ok := m["$oid"]
108+
if !ok {
109+
return errors.New("not an extended JSON ObjectID")
110+
}
111+
str, ok = oid.(string)
112+
if !ok {
113+
return errors.New("not an extended JSON ObjectID")
114+
}
99115
}
100116

101117
if len(str) != 24 {

0 commit comments

Comments
 (0)