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) {
77
77
return oid , nil
78
78
}
79
79
80
+ // MarshalJSON returns the ObjectID as a string
81
+ func (id ObjectID ) MarshalJSON () ([]byte , error ) {
82
+ return json .Marshal (id .Hex ())
83
+ }
84
+
80
85
// UnmarshalJSON populates the byte slice with the ObjectID. If the byte slice is 64 bytes long, it
81
86
// will be populated with the hex representation of the ObjectID. If the byte slice is twelve bytes
82
87
// 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 {
88
93
copy (id [:], b )
89
94
default :
90
95
// Extended JSON
91
- m := make ( map [ string ] string )
92
- err := json .Unmarshal (b , & m )
96
+ var res interface {}
97
+ err := json .Unmarshal (b , & res )
93
98
if err != nil {
94
99
return err
95
100
}
96
- str , ok := m [ "$oid" ]
101
+ str , ok := res .( string )
97
102
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
+ }
99
115
}
100
116
101
117
if len (str ) != 24 {
You can’t perform that action at this time.
0 commit comments