go-zero/core/jsonx/json.go

66 lines
1.4 KiB
Go
Raw Permalink Normal View History

2020-07-26 17:09:05 +08:00
package jsonx
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strings"
)
2021-02-20 16:59:31 +08:00
// Marshal marshals v into json bytes.
func Marshal(v any) ([]byte, error) {
2020-07-26 17:09:05 +08:00
return json.Marshal(v)
}
2022-07-09 15:05:59 +08:00
// MarshalToString marshals v into a string.
func MarshalToString(v any) (string, error) {
2022-07-09 15:05:59 +08:00
data, err := Marshal(v)
if err != nil {
return "", err
}
return string(data), nil
}
2021-02-20 16:59:31 +08:00
// Unmarshal unmarshals data bytes into v.
func Unmarshal(data []byte, v any) error {
2020-07-26 17:09:05 +08:00
decoder := json.NewDecoder(bytes.NewReader(data))
if err := unmarshalUseNumber(decoder, v); err != nil {
return formatError(string(data), err)
}
return nil
}
2021-02-20 16:59:31 +08:00
// UnmarshalFromString unmarshals v from str.
func UnmarshalFromString(str string, v any) error {
2020-07-26 17:09:05 +08:00
decoder := json.NewDecoder(strings.NewReader(str))
if err := unmarshalUseNumber(decoder, v); err != nil {
return formatError(str, err)
}
return nil
}
2021-02-20 16:59:31 +08:00
// UnmarshalFromReader unmarshals v from reader.
func UnmarshalFromReader(reader io.Reader, v any) error {
2020-07-26 17:09:05 +08:00
var buf strings.Builder
teeReader := io.TeeReader(reader, &buf)
decoder := json.NewDecoder(teeReader)
if err := unmarshalUseNumber(decoder, v); err != nil {
return formatError(buf.String(), err)
}
return nil
}
func unmarshalUseNumber(decoder *json.Decoder, v any) error {
2020-07-26 17:09:05 +08:00
decoder.UseNumber()
return decoder.Decode(v)
}
func formatError(v string, err error) error {
2022-02-09 14:40:05 +08:00
return fmt.Errorf("string: `%s`, error: `%w`", v, err)
2020-07-26 17:09:05 +08:00
}