File tree Expand file tree Collapse file tree 1 file changed +20
-4
lines changed
Expand file tree Collapse file tree 1 file changed +20
-4
lines changed Original file line number Diff line number Diff 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 {
You can’t perform that action at this time.
0 commit comments