1、结构体转json
package main
import (
"encoding/json"
"fmt"
)
type Movie struct{
Title string `json:"title"`
Year int `json:"year"`
Price int `json:"rmb"`
Actors []string `json:"actors"`
}
func main() {
movie := Movie{"喜剧之王",2000,10,[]string{"xingye","zhangbozhi"}}
//结构体转json
jsonStr,err := json.Marshal(movie)
if err != nil {
fmt.Println("json marshal error",err)
return
}
fmt.Printf("jsonStr = %s\n",jsonStr)
}
2、json转结构体文章来源:https://www.toymoban.com/news/detail-820225.html
package main
import (
"encoding/json"
"fmt"
)
type Movie struct{
Title string `json:"title"`
Year int `json:"year"`
Price int `json:"rmb"`
Actors []string `json:"actors"`
}
func main() {
movie := Movie{"喜剧之王",2000,10,[]string{"xingye","zhangbozhi"}}
//结构体转json
jsonStr,err := json.Marshal(movie)
if err != nil {
fmt.Println("json marshal error",err)
return
}
fmt.Printf("jsonStr = %s\n",jsonStr)
//解码的过程 json转结构体
//jsonStr = {"title":"喜剧之王","year":2000,"rmb":10,"actors":["xingye","zhangbozhi"]}
myMovie := Movie{}
err = json.Unmarshal(jsonStr,&myMovie)
if err != nil {
fmt.Println("json unmarshal error",err)
return
}
fmt.Printf("%v\n",myMovie)
}
文章来源地址https://www.toymoban.com/news/detail-820225.html
到了这里,关于go语言(十七)----json的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!