2020-07-26 17:09:05 +08:00
|
|
|
package mapping
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
|
2022-01-04 15:51:32 +08:00
|
|
|
"github.com/zeromicro/go-zero/core/jsonx"
|
2020-07-26 17:09:05 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
const jsonTagKey = "json"
|
|
|
|
|
|
|
|
var jsonUnmarshaler = NewUnmarshaler(jsonTagKey)
|
|
|
|
|
2021-02-20 23:18:22 +08:00
|
|
|
// UnmarshalJsonBytes unmarshals content into v.
|
2023-01-24 16:32:02 +08:00
|
|
|
func UnmarshalJsonBytes(content []byte, v any, opts ...UnmarshalOption) error {
|
2022-12-08 22:01:36 +08:00
|
|
|
return unmarshalJsonBytes(content, v, getJsonUnmarshaler(opts...))
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
2021-12-22 20:24:55 +08:00
|
|
|
// UnmarshalJsonMap unmarshals content from m into v.
|
2023-01-24 16:32:02 +08:00
|
|
|
func UnmarshalJsonMap(m map[string]any, v any, opts ...UnmarshalOption) error {
|
2022-12-08 22:01:36 +08:00
|
|
|
return getJsonUnmarshaler(opts...).Unmarshal(m, v)
|
2021-12-22 20:24:55 +08:00
|
|
|
}
|
|
|
|
|
2021-02-20 23:18:22 +08:00
|
|
|
// UnmarshalJsonReader unmarshals content from reader into v.
|
2023-01-24 16:32:02 +08:00
|
|
|
func UnmarshalJsonReader(reader io.Reader, v any, opts ...UnmarshalOption) error {
|
2022-12-08 22:01:36 +08:00
|
|
|
return unmarshalJsonReader(reader, v, getJsonUnmarshaler(opts...))
|
|
|
|
}
|
|
|
|
|
|
|
|
func getJsonUnmarshaler(opts ...UnmarshalOption) *Unmarshaler {
|
|
|
|
if len(opts) > 0 {
|
|
|
|
return NewUnmarshaler(jsonTagKey, opts...)
|
|
|
|
}
|
|
|
|
|
|
|
|
return jsonUnmarshaler
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
2023-01-24 16:32:02 +08:00
|
|
|
func unmarshalJsonBytes(content []byte, v any, unmarshaler *Unmarshaler) error {
|
|
|
|
var m any
|
2020-07-26 17:09:05 +08:00
|
|
|
if err := jsonx.Unmarshal(content, &m); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return unmarshaler.Unmarshal(m, v)
|
|
|
|
}
|
|
|
|
|
2023-01-24 16:32:02 +08:00
|
|
|
func unmarshalJsonReader(reader io.Reader, v any, unmarshaler *Unmarshaler) error {
|
|
|
|
var m any
|
2020-07-26 17:09:05 +08:00
|
|
|
if err := jsonx.UnmarshalFromReader(reader, &m); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return unmarshaler.Unmarshal(m, v)
|
|
|
|
}
|