package main
import "fmt"
import "reflect"
import "encoding/json"
func main(){
//1、结构体转为json
res := new(Response)
res.Code = 200
res.Message = "success"
fmt.Println(res)
fmt.Println("将结构体生成json")
//转化完默认是[]uint8类型,需要转换为string类型才能正常输出json
cont,_ := json.Marshal(res)
fmt.Println(string(cont)) // 输出json
//2、map转为json
map1 := make(map[string]string)
fmt.Println(map1)
map1["name"] = "maozedong"
map1["address"] = "湖南"
fmt.Println(map1)
map_json, _ := json.Marshal(map1)
fmt.Println(reflect.TypeOf(map_json)) //[]uint8
fmt.Println(string(map_json)) //输出json
//1、json转map
json_string := `[{"Level":"debug","Msg":"订单不存在"},{"Level":"error","Msg":"Logic error"}]`
var m1 []map[string]string
json.Unmarshal([]byte(json_string), &m1)
fmt.Println("json 转为map:")
fmt.Println(m1) //输出map
//2、json转结构体
var json_struct []S1_struct
json.Unmarshal([]byte(json_string), &json_struct)
fmt.Println(json_struct) //输出结构体
//3、json结构体互转还支持tag映射
var json_struct2 []S2_struct
json.Unmarshal([]byte(json_string), &json_struct2)
fmt.Println(json_struct2) //输出映射后的结构体
for _,item := range json_struct2 {
fmt.Println(item.Message)
}
//4、同理,结构体转换为json也支持tag映射
var struct3 S2_struct
struct3.Message = "hello message"
struct3.LevelString = "hello level"
content,_ := json.Marshal(struct3)
fmt.Println(string(content)) //json的键将分别被映射为Level,Msg
}
type Response struct{
Code int
Message string
}
type S1_struct struct{
Level string
Msg string
}
type S2_struct struct{
LevelString string `json:"Level"` //json里的level映射到LevelString
Message string `json:"Msg"` //json里的Msg映射到Message
}