Go语言中,结构体和JSON互转
结构体转JSON
package main
import (
"encoding/json"
"fmt"
)
type Zhihu struct {
Article string
Goods int
}
func main() {
z := Zhihu{
Article: "Go语言结构体和JSON相互转换",
Goods: 100,
}
output, _ := json.Marshal(&z)
fmt.Println(string(output))
}
JSON转结构体
package main
import (
"encoding/json"
"fmt"
)
type Zhihu struct {
Article string
Goods int
}
func main() {
var s Zhihu
j := `{"Acrticle":"Go语言结构体和JSON相互转换","Goods":100}`
json.Unmarshal([]byte(j),&s)
fmt.Println(string(s.Acrticle))
fmt.Println(int(s.Goods))
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 30%!