我正在尝试解组json数据。内部的切片是故意没有引号,因为这是我从https获得的(在“之前”手动添加\)
data:="{\"queryEndTime\" : \"2017-11-15T14:39:00Z\", \"message\" : [{\"spamScore\":67,\"phishScore\":0}]}"
进入Message struct:
type Message struct {
QueryEndTime string `json:"queryEndTime"`
Message []string `json:"message"`
}
但是我得到了正确的QueryEndTime和空消息。我试图改变消息类型,但它总是保持空白
var message Message
json.Unmarshal([]byte(data), &message)
fmt.Printf("QueryEndTime: %s\nMessage: %s\n", message.QueryEndTime, message.Message)
QueryEndTime: 2017-11-15T14:39:00Z
Message: []
在go playground https://play.golang.org/p/on0_cSKb0c中查看。
答案 0 :(得分:2)
package main
import (
"encoding/json"
"fmt"
)
type Message struct {
QueryEndTime string `json:"queryEndTime"`
// you need to use a struct can use anon struct
Message []struct {
SpamScore int `json:"spamScore"`
PhishScore int `json:"phishScore"`
} `json:"message"`
}
func main() {
var message Message
// You can use backticks to for your example JSON, so that you don't have to escape anything.
data := `{
"queryEndTime" : "2017-11-15T14:39:00Z",
"message" : [
{"spamScore":67, "phishScore":0}
]
}`
// please check for errors
err := json.Unmarshal([]byte(data), &message)
if err != nil {
fmt.Println(err)
}
// +v prints structs very nicely
fmt.Printf("%+v\n", message)
}
https://play.golang.org/p/Mu3WZCej3L
玩得开心!