[英]How to unmarshal this json string
I'm having some problem reading this type of json. 我在读这种类型的json时遇到了一些问题。
["Msg",{"cmd":"ack","id":"B81DA375B6C4AA49D262","ack":2,"from":"18094158994@c.us","to":"18099897215@c.us","t":1555446115}]
i try with many libraries. 我尝试了很多图书馆。
type SEND struct {
Mgs string `json:"Msg"`
//SEND MSG
}
type MSG struct {
CMD string `json:"cmd"`
ID string `json:"id"`
ACK int `json:"ack"`
FROM string `json:"from"`
TO string `json:"to"`
T int64 `json:"t"`
}
func main() {
data := `["Msg",{"cmd":"ack","id":"B81DA375B6C4AA49D262","ack":2,"from":"18094158994@c.us","to":"18099897215@c.us","t":1555446115}] `
var dd SEND
err := json.Valid([]byte(data))
fmt.Println("Is valid XML?->", err)
json.Unmarshal([]byte(data), &dd)
fmt.Println("1", dd)
fmt.Println("2", dd.Mgs)
}
Al always a receive empty and the json it's valid Al总是接收空,json是有效的
Is valid XML?-> true
1 {}
2 EMPTY
In this case you have array with string
and object
in your json, so you have to use interface{}
on golang side, must be something like: 在这种情况下,你的json中有
string
和object
数组,所以你必须在golang端使用interface{}
,必须是这样的:
package main
import (
"encoding/json"
"fmt"
)
func main() {
data := `["Msg",{"cmd":"ack","id":"B81DA375B6C4AA49D262","ack":2,"from":"18094158994@c.us","to":"18099897215@c.us","t":1555446115}] `
var d []interface{}
err := json.Unmarshal([]byte(data), &d)
fmt.Printf("err: %v \n", err)
fmt.Printf("d: %#v \n", d[0])
fmt.Printf("d: %#v \n", d[1])
}
Result will look like: 结果如下:
err: <nil>
d: "Msg"
d: map[string]interface {}{"id":"B81DA375B6C4AA49D262", "ack":2, "from":"18094158994@c.us", "to":"18099897215@c.us", "t":1.555446115e+09, "cmd":"ack"}
So 1st element in slice d
is string Msg
, 因此,片
d
第一个元素是字符串Msg
,
and 2nd element in slice is map map[string]interface {}
and now you can do something else with this map. 切片中的第二个元素是map
map[string]interface {}
,现在你可以用这个地图做其他事了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.