-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4_marshallers_test.go
More file actions
58 lines (47 loc) · 1.68 KB
/
Copy path4_marshallers_test.go
File metadata and controls
58 lines (47 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Package json_test demonstrates custom JSON marshaling in encoding/json/v2 using MarshalFunc
// for type-specific serialization logic without implementing the Marshaler interface.
//
// This file shows:
// - Using jsonv2.MarshalFunc for custom type serialization
// - Custom marshaling example: Converting musical notation to Unicode symbols (♯, ♭, °)
// - Type-safe custom marshaling without modifying the original type
package json_test
import (
jsonv2 "encoding/json/v2"
"fmt"
"strings"
"testing"
)
type Note string
// noteMarshalFunc is a custom JSON marshaler for Note types that converts musical note notation
// to Unicode symbols (# to ♯, B to ♭, etc.) and normalizes chord notation (MAJ to Maj, M to m, DIM to °).
// Special handling for notes starting with "B" to distinguish flat(♭) notes from B notes.
var noteMarshalFunc = jsonv2.MarshalFunc(func(n Note) ([]byte, error) {
replacer := strings.NewReplacer(
"X", "B",
"#", "♯",
"B", "♭",
"MAJ", "Maj",
"M", "m",
"DIM", "°",
)
str := strings.ToUpper(string(n))
if strings.HasPrefix(str, "B") {
str = strings.Replace(str, "B", "X", 1)
}
str = replacer.Replace(str)
return fmt.Append(nil, `"`+str+`"`), nil
})
// TestMarshalCustomType demonstrates using jsonv2.MarshalFunc to provide custom marshaling logic
// for the Note type, converting musical notation (Gbmaj7) to Unicode symbols (G♭Maj7).
func TestMarshalCustomType(t *testing.T) {
n := Note("Gbmaj7")
data := struct {
Name Note
}{Name: n}
b, _ := jsonv2.Marshal(data, jsonv2.WithMarshalers(noteMarshalFunc))
expected := `{"Name":"G♭Maj7"}`
if string(b) != expected {
t.Errorf("expected %q, got %q", expected, string(b))
}
}