Support RawMessage

This commit is contained in:
Masaaki Goshima 2020-08-11 18:11:13 +09:00
parent 0943ec9fb8
commit 371fbf2403
1 changed files with 23 additions and 0 deletions

23
json.go
View File

@ -2,6 +2,7 @@ package json
import ( import (
"bytes" "bytes"
"errors"
"strconv" "strconv"
) )
@ -294,3 +295,25 @@ func (n Number) Float64() (float64, error) {
func (n Number) Int64() (int64, error) { func (n Number) Int64() (int64, error) {
return strconv.ParseInt(string(n), 10, 64) return strconv.ParseInt(string(n), 10, 64)
} }
// RawMessage is a raw encoded JSON value.
// It implements Marshaler and Unmarshaler and can
// be used to delay JSON decoding or precompute a JSON encoding.
type RawMessage []byte
// MarshalJSON returns m as the JSON encoding of m.
func (m RawMessage) MarshalJSON() ([]byte, error) {
if m == nil {
return []byte("null"), nil
}
return m, nil
}
// UnmarshalJSON sets *m to a copy of data.
func (m *RawMessage) UnmarshalJSON(data []byte) error {
if m == nil {
return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
}
*m = append((*m)[0:0], data...)
return nil
}