1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 08:32:40 +08:00

名称转换

This commit is contained in:
2022-04-22 14:45:58 +08:00
parent f7df1f1668
commit bf99bebb07
5 changed files with 42 additions and 59 deletions

View File

@ -1,54 +0,0 @@
package json
import (
"reflect"
"github.com/charlienet/go-mixed/bytesconv"
)
// 结构转换为json字符串
func StructToJsonIndent(obj any) string {
b, _ := MarshalIndent(obj, "", " ")
return bytesconv.BytesToString(b)
}
// 结构转换为json字符串
func StructToJson(obj any) string {
b, _ := Marshal(obj)
return bytesconv.BytesToString(b)
}
func StructToMap(obj any) map[string]any {
typ := reflect.TypeOf(obj)
kind := typ.Kind()
if kind == reflect.Map {
return toMap(obj)
}
val := reflect.ValueOf(obj)
m := make(map[string]any)
for i := 0; i < val.NumField(); i++ {
m[typ.Field(i).Name] = val.Field(i).Interface()
}
return m
}
func StructToMapViaJson(obj any) map[string]any {
m := make(map[string]any)
j, _ := Marshal(obj)
_ = Unmarshal(j, &m)
return m
}
func toMap(obj any) map[string]any {
if h, ok := obj.(map[string]any); ok {
return h
}
return StructToMapViaJson(obj)
}

18
json/struct_test.go Normal file
View File

@ -0,0 +1,18 @@
package json
import (
"testing"
)
func TestMapModify(t *testing.T) {
m := map[string]string{
"A": "A",
}
modify(m)
t.Log(m)
}
func modify(m map[string]string) {
m["B"] = "bbb"
}