golang的json操作
本文内容纲要:
packagemain
import(
"encoding/json"
"fmt"
"os"
)
typeConfigStructstruct{
Hoststring`json:"host"`
Portint`json:"port"`
AnalyticsFilestring`json:"analytics_file"`
StaticFileVersionint`json:"static_file_version"`
StaticDirstring`json:"static_dir"`
TemplatesDirstring`json:"templates_dir"`
SerTcpSocketHoststring`json:"serTcpSocketHost"`
SerTcpSocketPortint`json:"serTcpSocketPort"`
Fruits[]string`json:"fruits"`
}
typeOtherstruct{
SerTcpSocketHoststring`json:"serTcpSocketHost"`
SerTcpSocketPortint`json:"serTcpSocketPort"`
Fruits[]string`json:"fruits"`
}
funcmain(){
jsonStr:=`{"host":"http://localhost:9090","port":9090,"analytics_file":"","static_file_version":1,"static_dir":"E:/Project/goTest/src/","templates_dir":"E:/Project/goTest/src/templates/","serTcpSocketHost":":12340","serTcpSocketPort":12340,"fruits":["apple","peach"]}`
//jsonstr转map
vardatmap[string]interface{}
iferr:=json.Unmarshal([]byte(jsonStr),&dat);err==nil{
fmt.Println("==============jsonstr转map=======================")
fmt.Println(dat)
fmt.Println(dat["host"])
}
//jsonstr转struct
varconfigConfigStruct
iferr:=json.Unmarshal([]byte(jsonStr),&config);err==nil{
fmt.Println("================jsonstr转struct==")
fmt.Println(config)
fmt.Println(config.Host)
}
//jsonstr转struct(部份字段)
varpartOther
iferr:=json.Unmarshal([]byte(jsonStr),&part);err==nil{
fmt.Println("================jsonstr转struct==")
fmt.Println(part)
fmt.Println(part.SerTcpSocketPort)
}
//struct到jsonstr
ifb,err:=json.Marshal(config);err==nil{
fmt.Println("================struct到jsonstr==")
fmt.Println(string(b))
}
//map到jsonstr
fmt.Println("================map到jsonstr=====================")
enc:=json.NewEncoder(os.Stdout)
enc.Encode(dat)
//array到jsonstr
arr:=[]string{"hello","apple","python","golang","base","peach","pear"}
lang,err:=json.Marshal(arr)
iferr==nil{
fmt.Println("================array到jsonstr==")
fmt.Println(string(lang))
}
//json到[]string
varwo[]string
iferr:=json.Unmarshal(lang,&wo);err==nil{
fmt.Println("================json到[]string==")
fmt.Println(wo)
}
}
本文内容总结:
原文链接:https://www.cnblogs.com/go-ios/p/3906251.html热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短