@@ -32,13 +32,22 @@ type Interface interface {
3232}
3333
3434var (
35- // DefaultJSONHandler default json handler
36- DefaultJSONHandler Interface = JSONiter { jsoniter . ConfigCompatibleWithStandardLibrary }
35+ // DefaultJSONHandler default json handler - uses JSON v2 if available, otherwise JSONiter
36+ DefaultJSONHandler = getDefaultHandler ()
3737
3838 _ Interface = StdJSON {}
3939 _ Interface = JSONiter {}
40+ _ Interface = JSONv2 {}
4041)
4142
43+ // getDefaultHandler returns the expected JSON implementation
44+ func getDefaultHandler () Interface {
45+ if isJSONv2Available () {
46+ return JSONv2 {}
47+ }
48+ return JSONiter {jsoniter .ConfigCompatibleWithStandardLibrary }
49+ }
50+
4251// StdJSON implements Interface via encoding/json
4352type StdJSON struct {}
4453
@@ -97,6 +106,47 @@ func (j JSONiter) Indent(dst *bytes.Buffer, src []byte, prefix, indent string) e
97106 return json .Indent (dst , src , prefix , indent )
98107}
99108
109+ // JSONv2 implements Interface via encoding/json/v2
110+ // Requires GOEXPERIMENT=jsonv2 to be set at build time
111+ type JSONv2 struct {}
112+
113+ // Marshal implements Interface using JSON v2 - fallback if v2 is not available
114+ func (JSONv2 ) Marshal (v any ) ([]byte , error ) {
115+ if ! isJSONv2Available () {
116+ return json .Marshal (v )
117+ }
118+ return marshalV2 (v )
119+ }
120+
121+ // Unmarshal implements Interface using JSON v2 - fallback if v2 is not available
122+ func (JSONv2 ) Unmarshal (data []byte , v any ) error {
123+ if ! isJSONv2Available () {
124+ return json .Unmarshal (data , v )
125+ }
126+ return unmarshalV2 (data , v )
127+ }
128+
129+ // NewEncoder implements Interface using JSON v2 - fallback if v2 is not available
130+ func (JSONv2 ) NewEncoder (writer io.Writer ) Encoder {
131+ if ! isJSONv2Available () {
132+ return json .NewEncoder (writer )
133+ }
134+ return newEncoderV2 (writer )
135+ }
136+
137+ // NewDecoder implements Interface using JSON v2 - fallback if v2 is not available
138+ func (JSONv2 ) NewDecoder (reader io.Reader ) Decoder {
139+ if ! isJSONv2Available () {
140+ return json .NewDecoder (reader )
141+ }
142+ return newDecoderV2 (reader )
143+ }
144+
145+ // Indent implements Interface using standard library (JSON v2 doesn't have Indent yet)
146+ func (JSONv2 ) Indent (dst * bytes.Buffer , src []byte , prefix , indent string ) error {
147+ return json .Indent (dst , src , prefix , indent )
148+ }
149+
100150// Marshal converts object as bytes
101151func Marshal (v any ) ([]byte , error ) {
102152 return DefaultJSONHandler .Marshal (v )
0 commit comments