Skip to content

Commit b20691d

Browse files
authored
fix: Deserialize using a generic approach. (#121)
1 parent 6ea1fbe commit b20691d

File tree

3 files changed

+15
-17
lines changed

3 files changed

+15
-17
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,4 @@ _cgo_export.*
2020
_testmain.go
2121

2222
*.exe
23+
.idea

threadsafe_test.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -540,7 +540,17 @@ func Test_UnmarshalJSON(t *testing.T) {
540540
t.Errorf("Expected no difference, got: %v", expected.Difference(actual))
541541
}
542542
}
543-
543+
func TestThreadUnsafeSet_UnmarshalJSON(t *testing.T) {
544+
expected := NewThreadUnsafeSet[int64](1, 2, 3)
545+
actual := NewThreadUnsafeSet[int64]()
546+
err := actual.UnmarshalJSON([]byte(`[1, 2, 3]`))
547+
if err != nil {
548+
t.Errorf("Error should be nil: %v", err)
549+
}
550+
if !expected.Equal(actual) {
551+
t.Errorf("Expected no difference, got: %v", expected.Difference(actual))
552+
}
553+
}
544554
func Test_MarshalJSON(t *testing.T) {
545555
expected := NewSet(
546556
[]string{

threadunsafe.go

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ SOFTWARE.
2626
package mapset
2727

2828
import (
29-
"bytes"
3029
"encoding/json"
3130
"fmt"
3231
"strings"
@@ -311,24 +310,12 @@ func (s threadUnsafeSet[T]) MarshalJSON() ([]byte, error) {
311310
// UnmarshalJSON recreates a set from a JSON array, it only decodes
312311
// primitive types. Numbers are decoded as json.Number.
313312
func (s threadUnsafeSet[T]) UnmarshalJSON(b []byte) error {
314-
var i []any
315-
316-
d := json.NewDecoder(bytes.NewReader(b))
317-
d.UseNumber()
318-
err := d.Decode(&i)
313+
var i []T
314+
err := json.Unmarshal(b, &i)
319315
if err != nil {
320316
return err
321317
}
322-
323-
for _, v := range i {
324-
switch t := v.(type) {
325-
case T:
326-
s.add(t)
327-
default:
328-
// anything else must be skipped.
329-
continue
330-
}
331-
}
318+
s.Append(i...)
332319

333320
return nil
334321
}

0 commit comments

Comments
 (0)