github.com/LanceLRQ/deer-common@v0.0.9-0.20210319081233-e8222ac018a8/utils/json.go (about) 1 package utils 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 ) 8 9 func ObjectToJSONStringFormatted(conf interface{}) string { 10 b, err := json.Marshal(conf) 11 if err != nil { 12 return fmt.Sprintf("%+v", conf) 13 } 14 var out bytes.Buffer 15 err = json.Indent(&out, b, "", " ") 16 if err != nil { 17 return fmt.Sprintf("%+v", conf) 18 } 19 return out.String() 20 } 21 22 func ObjectToJSONByte(obj interface{}) []byte { 23 b, err := json.Marshal(obj) 24 if err != nil { 25 return []byte("{}") 26 } 27 return b 28 } 29 30 func ObjectToJSONString(obj interface{}) string { 31 b, err := json.Marshal(obj) 32 if err != nil { 33 return "{}" 34 } else { 35 return string(b) 36 } 37 } 38 39 func JSONStringObject(jsonStr string, obj interface{}) bool { 40 return JSONBytesObject([]byte(jsonStr), obj) 41 } 42 43 func JSONBytesObject(jsonBytes []byte, obj interface{}) bool { 44 err := json.Unmarshal(jsonBytes, &obj) 45 if err != nil { 46 return false 47 } else { 48 return true 49 } 50 }