package utils
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/json-iterator/go/extra"
)
func init() {
extra.RegisterFuzzyDecoders()
}
// json 包转换后的整数类型是 Float64
func IsNumber(value interface{}) bool {
switch value.(type) {
case int, int32, int64, int8, json.Number, float64, float32, uint, uint8, uint32, uint64:
return true
}
return false
}
func IsArray(value interface{}) bool {
kind := reflect.TypeOf(value).Kind()
return kind == reflect.Slice || kind == reflect.Array
}
func IsString(value interface{}) bool {
switch value.(type) {
case string:
return true
}
return false
}
func IsObject(value interface{}) bool {
return reflect.TypeOf(value).Kind() == reflect.Map
}
func StringArrToIntArr(strArr []string) ([]int64, bool) {
numArr := make([]int64, 0, len(strArr))
for _, vec := range strArr {
num, err := strconv.ParseInt(vec, 10, 64)
if err == nil {
numArr = append(numArr, num)
} else {
return nil, false
}
}
return numArr, true
}
func ConvertToString(value interface{}) string {
return fmt.Sprintf("%v", value)
}
func ConvertToInt64(value interface{}) int64 {
switch value.(type) {
case json.Number:
num, _ := value.(json.Number).Int64()
return num
case float32, float64:
return int64(value.(float64))
case int, int8, int16, int32, int64:
return reflect.ValueOf(value).Int()
}
return 0
}
func ConvertToArray(value interface{}) []interface{} {
if value, ok := value.([]interface{}); ok {
return value
}
return nil
}
func ConvertToMap(value interface{}) map[string]interface{} {
if value, ok := value.(map[string]interface{}); ok {
return value
}
return nil
}
func JsonArrayToIntArray(jsonStr string) ([]int64, error) {
doc := make([]int64, 0)
err := json.Unmarshal([]byte(jsonStr), &doc)
if err != nil {
return nil, err
}
return doc, nil
}
func SplitToIntArr(str string) ([]int64, bool) {
vector := strings.Split(str, ",")
if numArr, ok := StringArrToIntArr(vector); ok {
return numArr, true
} else {
return nil, false
}
}
// UnmarshalNumber 反序列化 把String变成对象
func UnmarshalNumber(jsonStr string, object interface{}) error {
d := json.NewDecoder(bytes.NewReader([]byte(jsonStr)))
d.UseNumber()
err := d.Decode(object)
return err
}
【Go】json工具类
最新推荐文章于 2024-06-13 22:15:00 发布