json.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package utils
  2. import (
  3. "encoding/json"
  4. "strconv"
  5. "strings"
  6. "zhiyuan/pkg/logger"
  7. )
  8. type JsonDecode string
  9. func (val JsonDecode) To(ret interface{}) {
  10. GetJsonDecode(val).Decode(&ret)
  11. }
  12. func (val JsonDecode) ToMap() map[string]interface{} {
  13. dest := make(map[string]interface{})
  14. GetJsonDecode(val).Decode(&dest)
  15. return dest
  16. }
  17. func (val JsonDecode) ToString() string {
  18. s, _ := strconv.Unquote(string(val))
  19. return s
  20. }
  21. func (val JsonDecode) ToMapSlice() []map[string]interface{} {
  22. dest := make([]map[string]interface{}, 0)
  23. GetJsonDecode(val).Decode(&dest)
  24. return dest
  25. }
  26. func (val JsonDecode) ToStrSlice() []string {
  27. dest := make([]string, 0)
  28. GetJsonDecode(val).Decode(&dest)
  29. return dest
  30. }
  31. func (val JsonDecode) ToIntSlice() []int {
  32. dest := make([]int, 0)
  33. GetJsonDecode(val).Decode(&dest)
  34. return dest
  35. }
  36. func (val JsonDecode) ToMapStr() string {
  37. var dest string
  38. GetJsonDecode(val).Decode(&dest)
  39. return dest
  40. }
  41. func GetJsonDecode(val JsonDecode) *json.Decoder {
  42. decoder := json.NewDecoder(strings.NewReader(string(val)))
  43. decoder.UseNumber()
  44. return decoder
  45. }
  46. func JsonEncode(data interface{}) string {
  47. jsonData, err := json.Marshal(data)
  48. if err != nil {
  49. logger.Sugar.Error(err)
  50. return ""
  51. }
  52. return string(jsonData)
  53. }