package json import ( jsoniter "github.com/json-iterator/go" "reflect" ) // var json = jsoniter.ConfigFastest var json = jsoniter.Config{ EscapeHTML: false, SortMapKeys: true, MarshalFloatWith6Digits: true, // will lose precession ObjectFieldMustBeSimpleString: true, // do not unescape object field }.Froze() //goland:noinspection GoUnusedGlobalVariable var ( Get = json.Get Marshal = json.Marshal Unmarshal = json.Unmarshal UnmarshalFromString = json.UnmarshalFromString MarshalIndent = json.MarshalIndent NewDecoder = json.NewDecoder NewEncoder = json.NewEncoder ) // MarshalToString JSON编码为字符串 // func MarshalToString(v interface{}) string { s, err := jsoniter.MarshalToString(v) if err != nil { return "" } return s } func Struct2MapByKeepFieldName(obj interface{}) map[string]interface{} { t := reflect.TypeOf(obj) v := reflect.ValueOf(obj) var data = make(map[string]interface{}) for i := 0; i < t.NumField(); i++ { data[t.Field(i).Name] = v.Field(i).Interface() } return data } func Struct2MapByJsonName(obj interface{}) (map[string]interface{}, error) { marshal, err := json.Marshal(obj) if err != nil { return nil, err } var data map[string]interface{} err = json.Unmarshal(marshal, &data) if err != nil { return nil, err } return data, nil } func MapToStruct(m map[string]interface{}, o interface{}) error { marshal, err := json.Marshal(m) if err != nil { return err } err = json.Unmarshal(marshal, o) if err != nil { return err } return nil }