github.com/gogf/gf@v1.16.9/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/gogf/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 16 // Marshal adapts to json/encoding Marshal API. 17 // 18 // Marshal returns the JSON encoding of v, adapts to json/encoding Marshal API 19 // Refer to https://godoc.org/encoding/json#Marshal for more information. 20 func Marshal(v interface{}) ([]byte, error) { 21 return json.Marshal(v) 22 } 23 24 // MarshalIndent same as json.MarshalIndent. Prefix is not supported. 25 func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { 26 return json.MarshalIndent(v, prefix, indent) 27 } 28 29 // Unmarshal adapts to json/encoding Unmarshal API 30 // 31 // Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. 32 // Refer to https://godoc.org/encoding/json#Unmarshal for more information. 33 func Unmarshal(data []byte, v interface{}) error { 34 return json.Unmarshal(data, v) 35 } 36 37 // UnmarshalUseNumber decodes the json data bytes to target interface using number option. 38 func UnmarshalUseNumber(data []byte, v interface{}) error { 39 decoder := NewDecoder(bytes.NewReader(data)) 40 decoder.UseNumber() 41 return decoder.Decode(v) 42 } 43 44 // NewEncoder same as json.NewEncoder 45 func NewEncoder(writer io.Writer) *json.Encoder { 46 return json.NewEncoder(writer) 47 } 48 49 // NewDecoder adapts to json/stream NewDecoder API. 50 // 51 // NewDecoder returns a new decoder that reads from r. 52 // 53 // Instead of a json/encoding Decoder, an Decoder is returned 54 // Refer to https://godoc.org/encoding/json#NewDecoder for more information. 55 func NewDecoder(reader io.Reader) *json.Decoder { 56 return json.NewDecoder(reader) 57 } 58 59 // Valid reports whether data is a valid JSON encoding. 60 func Valid(data []byte) bool { 61 return json.Valid(data) 62 }