package main
import (
"encoding/json"
"fmt"
)
//json转变为结构体
type IT struct{
Company string `json:"company"`
Subjects []string `json:"subjects"`
IsOk bool `json:",isok"` //二次编码
Price float32 `json:"price"`
}
func main(){
//1定义一个json
jsonBuf:=`
{
"company": "zze",
"subjects": [
"go",
"java",
"python"
],
"isOk": true,
"price": 11.22
}
`
//2定义一个结构体变量
var tmp IT
//3转换方,注意参数类型
err:=json.Unmarshal([]byte(jsonBuf),&tmp)
//4异常处理
if err!=nil{
fmt.Println(err)
return
}
fmt.Println("tep=",tmp)
fmt.Println("tmp.company=",tmp.Company)
//5 结构体单个元素接收
type IT2 struct{
Subjects []string `json:subjects`
}
var tmp2 IT2
err2:=json.Unmarshal([]byte(jsonBuf),&tmp2)
if err2!=nil{
fmt.Println(err2)
return
}
fmt.Println("tmp2=",tmp2)
}
4.19 go json解析到结构体
猜你喜欢
转载自blog.csdn.net/h4241778/article/details/105347872
今日推荐
周排行