golang解析json格式
golang解析json格式 项目中客户端和服务端的交互数据部分为json,因此在服务端就得解析,复杂的json解析起来其实还是挺费劲的。 {"sn":1,"ls":false,"bg":0,"ed":0,"ws":[{"bg":0,"cw":[{"sc":0,"w":"还"}]},{"bg":0,21)">"有点"}]},21)">"眼熟"}]}]}
需要将json格式中的w字段取出来,并且拼成结果串进行展示
初步实现如下: func RecResultJsonToPlain() {
var recResult string
var dat map[string]interface{}
json.Unmarshal([]byte(json_str),&dat)
if v,ok := dat["ws"]; ok {
ws := v.([]interface{})
for i,wsItem := range ws {
wsMap := wsItem.(interface{})
if vCw,ok := wsMap["cw"]; ok {
cw := vCw.([]interface{})
range cw {
cwItemMap := cwItem.(interface{})
if w,ok := cwItemMap["w"]; ok {
recResult = recResult + w.(string)
}
}
}
}
}
fmt.Println(recResult)
}
这样实现,一层一层去转换类型,再去获取元素有点麻烦。既然是已知的json数据结构,那么可以定义好结构体,再去进行解析。 type CWItem struct {
SC int32 `json:"sc"`
W string `json:"w"`
}
type WSItem struct {
CW []CWItem
}
type IatResult struct {
SN int32 `json:"sn"`
LS bool `json:"ls"`
BG int32 `json:"bg"`
ED int32 `json:"ed"`
WS []WSItem `json:"ws"`
}
type AutoGenerated struct {
Sn int `json:"sn"`
Ls bool `json:"ls"`
Bg "bg"`
Ed "ed"`
Ws []struct {
Bg "bg"`
Cw []struct {
Sc "sc"`
W string `json:"w"`
} `json:"cw"`
} `json:"ws"`
}
func RecResultJsonToPlain(jsonResult []byte)(recPlainResult string) {
var r IatResult
json.Unmarshal(jsonResult,&r)
for _,255)">range r.WS {
range wsItem.CW {
recPlainResult = recPlainResult + cwItem.W
}
}
return recPlainResult
}
上面的元素有 {"Asks": [[21,1],[22,1]] ,"Bids": [[20,[19,1]]}
搜索到一段代码如下,重新实现了UnmarshalJSON package main
import (
"encoding/json"
"fmt"
)
type Message struct {
Asks []Order `json:"Bids"`
Bids []Order `json:"Asks"`
}
type Order struct {
Price float64
Volume float64
}
func (o *Order) UnmarshalJSON(data []byte) error {
var v [2]float64
if err := json.Unmarshal(data,&v); err != nil {
return err
}
o.Price = v[0]
o.Volume = v[1]
return nil
}
func main() {
b := []byte(`{"Asks": [[21,1],[22,1]],"Bids": [[20,[19,1]]}`)
var m Message
if err := json.Unmarshal(b,&m); err != nil {
fmt.Println(err)
return
}
fmt.Printf("%#vn",m)
}
参考: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |