Go_14:GoLang中 json荠雕、map啦辐、struct 之間的相互轉(zhuǎn)化
https://www.cnblogs.com/liang1101/p/6741262.html
golang中struct、json、map互相轉(zhuǎn)化
2018年05月07日 23:14:14 小拳頭 閱讀數(shù):7354
<article class="baidu_pl" style="box-sizing: inherit; outline: 0px; display: block; position: relative; padding-top: 16px;">
版權(quán)聲明:本文為博主原創(chuàng)文章槽袄,轉(zhuǎn)載請(qǐng)標(biāo)明原文地址,謝謝 _ https://blog.csdn.net/xiaoquantouer/article/details/80233177
一锋谐、Json和struct互換
(1)Json轉(zhuǎn)struct例子:
package main import ( "fmt" "encoding/json") type People struct { Name string `json:"name_title"` Age int `json:"age_size"`} func JsonToStructDemo(){ jsonStr := ` { "name_title": "jqw" "age_size":12 } ` var people People json.Unmarshal([]byte(jsonStr), &people) fmt.Println(people)} func main(){ JsonToStructDemo()}
輸出:
注意json里面的key和struct里面的key要一致遍尺,struct中的key的首字母必須大寫(xiě),而json中大小寫(xiě)都可以涮拗。
(2)struct轉(zhuǎn)json
在結(jié)構(gòu)體中引入tag標(biāo)簽乾戏,這樣匹配的時(shí)候json串對(duì)應(yīng)的字段名需要與tag標(biāo)簽中定義的字段名匹配,當(dāng)然tag中定義的名稱(chēng)不需要首字母大寫(xiě)多搀,且對(duì)應(yīng)的json串中字段名仍然大小寫(xiě)不敏感歧蕉。此時(shí),結(jié)構(gòu)體中對(duì)應(yīng)的字段名可以不用和匹配的一致康铭,但是首字母必須大寫(xiě)惯退,只有大寫(xiě)才是可對(duì)外提供訪問(wèn)的。
例子:
package main import ( "fmt" "encoding/json") type People struct { Name string `json:"name_title"` Age int `json:"age_size"`} func StructToJsonDemo(){ p := People{ Name: "jqw", Age: 18, } jsonBytes, err := json.Marshal(p) if err != nil { fmt.Println(err) } fmt.Println(string(jsonBytes))} func main(){ StructToJsonDemo()}
輸出:
二从藤、json和map互轉(zhuǎn)
(1)json轉(zhuǎn)map例子:
func JsonToMapDemo(){ 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)}
輸出:
(2)map轉(zhuǎn)Json例子
func MapToJsonDemo1(){ 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))}
輸出:
例2:
func MapToJsonDemo2(){ b, _ := json.Marshal(map[string]int{"test":1, "try":2}) fmt.Println(string(b))}
輸出:
三催跪、map和struct互轉(zhuǎn)
(1)map轉(zhuǎn)struct
需要安裝一個(gè)第三方庫(kù)
在命令行中運(yùn)行: go get github.com/goinggo/mapstructure
例子:
func MapToStructDemo(){ 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)}
輸出
(2)struct轉(zhuǎn)map例子
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)}
輸出:
#############
map轉(zhuǎn)json
ptoken, _ := ParseToken(authtoken, []byte(JwtSecret))
fmt.Println("ptoken.Valid():",ptoken.Valid())
fmt.Println("token Claims:", ptoken)
tokenbyte,_:=json.Marshal(ptoken)
tokenstr:=string(tokenbyte)
fmt.Println(tokenstr)
//結(jié)構(gòu)體首字母必須大寫(xiě)
func main() {
app := iris.New()
app.Get("/", get)
app.Run(iris.Addr(":8080"))
}
type str struct {
Av string json:"av"
Bv int json:"bv"
}
func get(ctx iris.Context) {
strv:=str{Av:"abc",Bv:555}
jsons,_:=json.Marshal(strv)
json.Unmarshal(jsons,&strv)
ctx.JSON(strv)
}
type header struct {
Encryption string `json:"encryption"`
Timestamp int64 `json:"timestamp"`
Key string `json:"key"`
Partnercode int `json:"partnercode"`
}
//轉(zhuǎn)換成JSON字符串
headerO1 := header{
Encryption: "sha",
Timestamp: 1482463793,
Key: "2342874840784a81d4d9e335aaf76260",
Partnercode: 10025,
}
//jsons, _ := json.MarshalIndent(headerO1,"","") //轉(zhuǎn)換成JSON返回的是byte[]
jsons,_:=json.Marshal(headerO1)
fmt.Println(string(jsons)) // <--轉(zhuǎn)成string輸出
var data header
//json.Unmarshal([]byte(jsons),&data)
json.Unmarshal(jsons,&data)
fmt.Println(string(jsons))
ctx.JSON(data)