File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change @@ -99,6 +99,20 @@ func (id ObjectID) MarshalJSON() ([]byte, error) {
99
99
return json .Marshal (id .Hex ())
100
100
}
101
101
102
+ // MarshalText returns the ObjectID as text
103
+ // Implementing this allows us to use the ObjectID as a map key
104
+ // when marshalling json.
105
+ func (id ObjectID ) MarshalText () ([]byte , error ) {
106
+ return []byte (id .Hex ()), nil
107
+ }
108
+
109
+ // UnmarshalText converts a text ObjectID into a byte string
110
+ // Implementing this allows us to use the ObjectID as a map key
111
+ // when marshalling json.
112
+ func (id ObjectID ) UnmarshalText (b []byte ) error {
113
+ return id .UnmarshalJSON (b )
114
+ }
115
+
102
116
// UnmarshalJSON populates the byte slice with the ObjectID. If the byte slice is 24 bytes long, it
103
117
// will be populated with the hex representation of the ObjectID. If the byte slice is twelve bytes
104
118
// long, it will be populated with the BSON representation of the ObjectID. This method also accepts empty strings and
Original file line number Diff line number Diff line change @@ -172,6 +172,37 @@ func TestCounterOverflow(t *testing.T) {
172
172
require .Equal (t , uint32 (0 ), objectIDCounter )
173
173
}
174
174
175
+ func TestObjectID_MarshalJSONMap (t * testing.T ) {
176
+ type mapOID struct {
177
+ Map map [ObjectID ]string
178
+ }
179
+
180
+ oid := NewObjectID ()
181
+ expectedJson := []byte (fmt .Sprintf (`{"Map":{%q:"foo"}}` , oid .Hex ()))
182
+ data := mapOID {
183
+ Map : map [ObjectID ]string {oid : "foo" },
184
+ }
185
+
186
+ out , err := json .Marshal (& data )
187
+ require .NoError (t , err )
188
+ require .Equal (t , expectedJson , out )
189
+ }
190
+
191
+ func TestObjectID_UnmarshalJSONMap (t * testing.T ) {
192
+ type mapOID struct {
193
+ Map map [ObjectID ]string
194
+ }
195
+ oid := NewObjectID ()
196
+ mapOIDJson := []byte (fmt .Sprintf (`{"Map":{%q:"foo"}}` , oid .Hex ()))
197
+ expectedData := mapOID {
198
+ Map : map [ObjectID ]string {oid : "foo" },
199
+ }
200
+
201
+ data := mapOID {}
202
+ err := json .Unmarshal (mapOIDJson , & data )
203
+ require .NoError (t , err )
204
+ require .Equal (t , expectedData , data )
205
+ }
175
206
func TestObjectID_UnmarshalJSON (t * testing.T ) {
176
207
oid := NewObjectID ()
177
208
You can’t perform that action at this time.
0 commit comments