mirror of
https://github.com/gin-gonic/gin.git
synced 2026-09-04 22:53:34 +08:00
As an experiment, with a thought for how Gin might eventually migrate to
and use features from jsonv2, I have put together a new json/codec for
json/v2.
---
Selected with -tags jsonv2, and constrained to go1.27 &&
goexperiment.jsonv2 since encoding/json/v2 is still gated by the
experiment in 1.27 and GOEXPERIMENT=nojsonv2 makes it unimportable.
json.go negates that entire expression, mirroring how it already
negates sonic's OS constraint, so -tags jsonv2 on Go 1.25/1.26 falls
back to encoding/json rather than leaving API nil.
Uses json.DefaultOptionsV1() to keep behaviour identical to the v1
codec: v2's native defaults would render nil slices/maps as []/{} and
match member names case-sensitively, silently zeroing fields that
previously bound.
Fills three v1 gaps v2's API doesn't cover directly: UseNumber has no
exported option, so it's reproduced with a custom *any unmarshaler;
MarshalWrite omits Encoder.Encode's trailing newline; MarshalIndent
becomes jsontext.WithIndentPrefix + WithIndent.
42 lines
965 B
Go
42 lines
965 B
Go
// Copyright 2025 Gin Core Team. All rights reserved.
|
|
// Use of this source code is governed by a MIT style
|
|
// license that can be found in the LICENSE file.
|
|
|
|
//go:build !(jsonv2 && go1.27 && goexperiment.jsonv2) && !jsoniter && !go_json && !(sonic && (linux || windows || darwin))
|
|
|
|
package json
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
)
|
|
|
|
// Package indicates what library is being used for JSON encoding.
|
|
const Package = "encoding/json"
|
|
|
|
func init() {
|
|
API = jsonApi{}
|
|
}
|
|
|
|
type jsonApi struct{}
|
|
|
|
func (j jsonApi) Marshal(v any) ([]byte, error) {
|
|
return json.Marshal(v)
|
|
}
|
|
|
|
func (j jsonApi) Unmarshal(data []byte, v any) error {
|
|
return json.Unmarshal(data, v)
|
|
}
|
|
|
|
func (j jsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {
|
|
return json.MarshalIndent(v, prefix, indent)
|
|
}
|
|
|
|
func (j jsonApi) NewEncoder(writer io.Writer) Encoder {
|
|
return json.NewEncoder(writer)
|
|
}
|
|
|
|
func (j jsonApi) NewDecoder(reader io.Reader) Decoder {
|
|
return json.NewDecoder(reader)
|
|
}
|