json.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. // Package json provides json operations wrapping ignoring stdlib or third-party lib json.
  7. package json
  8. import (
  9. "bytes"
  10. "encoding/json"
  11. "io"
  12. )
  13. // Marshal adapts to json/encoding Marshal API.
  14. //
  15. // Marshal returns the JSON encoding of v, adapts to json/encoding Marshal API
  16. // Refer to https://godoc.org/encoding/json#Marshal for more information.
  17. func Marshal(v interface{}) ([]byte, error) {
  18. return json.Marshal(v)
  19. }
  20. // MarshalIndent same as json.MarshalIndent. Prefix is not supported.
  21. func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
  22. return json.MarshalIndent(v, prefix, indent)
  23. }
  24. // Unmarshal adapts to json/encoding Unmarshal API
  25. //
  26. // Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.
  27. // Refer to https://godoc.org/encoding/json#Unmarshal for more information.
  28. func Unmarshal(data []byte, v interface{}) error {
  29. return json.Unmarshal(data, v)
  30. }
  31. // UnmarshalUseNumber decodes the json data bytes to target interface using number option.
  32. func UnmarshalUseNumber(data []byte, v interface{}) error {
  33. decoder := NewDecoder(bytes.NewReader(data))
  34. decoder.UseNumber()
  35. return decoder.Decode(v)
  36. }
  37. // NewEncoder same as json.NewEncoder
  38. func NewEncoder(writer io.Writer) *json.Encoder {
  39. return json.NewEncoder(writer)
  40. }
  41. // NewDecoder adapts to json/stream NewDecoder API.
  42. //
  43. // NewDecoder returns a new decoder that reads from r.
  44. //
  45. // Instead of a json/encoding Decoder, an Decoder is returned
  46. // Refer to https://godoc.org/encoding/json#NewDecoder for more information.
  47. func NewDecoder(reader io.Reader) *json.Decoder {
  48. return json.NewDecoder(reader)
  49. }
  50. // Valid reports whether data is a valid JSON encoding.
  51. func Valid(data []byte) bool {
  52. return json.Valid(data)
  53. }