golang结构体map和json相互转换 2019-03-25 约 380 字 预计阅读 1 分钟 文章目录 golang结构体map和json相互转换 json转struct struct转json json 转 map map 转 json map 转struct struct 转map golang结构体map和json相互转换 json转struct 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package main import ( "fmt" "encoding/json" ) type People struct { Name string `json:"name_title"` Age int `json:"age_size"` } func main(){ jsonStr := ` { "name_title": "jqw" "age_size":12 } ` var people People json.Unmarshal([]byte(jsonStr), &people) fmt.Println(people) } struct转json 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package main import ( "fmt" "encoding/json" ) type People struct { Name string `json:"name_title"` Age int `json:"age_size"` } func main(){ p := People{ Name: "jqw", Age: 18, } jsonBytes, err := json.Marshal(p) if err != nil { fmt.Println(err) } fmt.Println(string(jsonBytes)) } json 转 map 1 2 3 4 5 6 7 8 9 10 11 12 13 14 unc main(){ jsonStr := ` { "name": "jqw", "age": 18 } ` var mapResult map[string]interface{} err := json.Unmarshal([]byte(jsonStr), &mapResult) if err != nil { fmt.Println("JsonToMapDemo err: ", err) } fmt.Println(mapResult) } map 转 json 1 2 3 4 5 6 7 8 9 10 11 12 13 14 func main(){ mapInstances := []map[string]interface{}{} instance_1 := map[string]interface{}{"name": "John", "age": 10} instance_2 := map[string]interface{}{"name": "Alex", "age": 12} mapInstances = append(mapInstances, instance_1, instance_2) jsonStr, err := json.Marshal(mapInstances) if err != nil { fmt.Println("MapToJsonDemo err: ", err) } fmt.Println(string(jsonStr)) } map 转struct 1 2 3 4 5 6 7 8 9 10 11 12 func main(){ mapInstance := make(map[string]interface{}) mapInstance["Name"] = "jqw" mapInstance["Age"] = 18 var people People err := mapstructure.Decode(mapInstance, &people) if err != nil { fmt.Println(err) } fmt.Println(people) } struct 转map 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 func StructToMapDemo(obj interface{}) map[string]interface{}{ obj1 := reflect.TypeOf(obj) obj2 := reflect.ValueOf(obj) var data = make(map[string]interface{}) for i := 0; i < obj1.NumField(); i++ { data[obj1.Field(i).Name] = obj2.Field(i).Interface() } return data } func TestStructToMap(){ student := Student{10, "jqw", 18} data := StructToMapDemo(student) fmt.Println(data) } 文章作者 gorpher 上次更新 2019-03-25