github.com/wangyougui/gf/v2@v2.6.5/internal/json/json.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 // Package json provides json operations wrapping ignoring stdlib or third-party lib json. 8 package json 9 10 import ( 11 "bytes" 12 "encoding/json" 13 "io" 14 15 "github.com/wangyougui/gf/v2/errors/gerror" 16 ) 17 18 // RawMessage is a raw encoded JSON value. 19 // It implements Marshaler and Unmarshaler and can 20 // be used to delay JSON decoding or precompute a JSON encoding. 21 type RawMessage = json.RawMessage 22 23 // Marshal adapts to json/encoding Marshal API. 24 // 25 // Marshal returns the JSON encoding of v, adapts to json/encoding Marshal API 26 // Refer to https://godoc.org/encoding/json#Marshal for more information. 27 func Marshal(v interface{}) (marshaledBytes []byte, err error) { 28 marshaledBytes, err = json.Marshal(v) 29 if err != nil { 30 err = gerror.Wrap(err, `json.Marshal failed`) 31 } 32 return 33 } 34 35 // MarshalIndent same as json.MarshalIndent. 36 func MarshalIndent(v interface{}, prefix, indent string) (marshaledBytes []byte, err error) { 37 marshaledBytes, err = json.MarshalIndent(v, prefix, indent) 38 if err != nil { 39 err = gerror.Wrap(err, `json.MarshalIndent failed`) 40 } 41 return 42 } 43 44 // Unmarshal adapts to json/encoding Unmarshal API 45 // 46 // Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. 47 // Refer to https://godoc.org/encoding/json#Unmarshal for more information. 48 func Unmarshal(data []byte, v interface{}) (err error) { 49 err = json.Unmarshal(data, v) 50 if err != nil { 51 err = gerror.Wrap(err, `json.Unmarshal failed`) 52 } 53 return 54 } 55 56 // UnmarshalUseNumber decodes the json data bytes to target interface using number option. 57 func UnmarshalUseNumber(data []byte, v interface{}) (err error) { 58 decoder := NewDecoder(bytes.NewReader(data)) 59 decoder.UseNumber() 60 err = decoder.Decode(v) 61 if err != nil { 62 err = gerror.Wrap(err, `json.UnmarshalUseNumber failed`) 63 } 64 return 65 } 66 67 // NewEncoder same as json.NewEncoder 68 func NewEncoder(writer io.Writer) *json.Encoder { 69 return json.NewEncoder(writer) 70 } 71 72 // NewDecoder adapts to json/stream NewDecoder API. 73 // 74 // NewDecoder returns a new decoder that reads from r. 75 // 76 // Instead of a json/encoding Decoder, a Decoder is returned 77 // Refer to https://godoc.org/encoding/json#NewDecoder for more information. 78 func NewDecoder(reader io.Reader) *json.Decoder { 79 return json.NewDecoder(reader) 80 } 81 82 // Valid reports whether data is a valid JSON encoding. 83 func Valid(data []byte) bool { 84 return json.Valid(data) 85 }