【发布时间】:2020-03-05 15:17:50
【问题描述】:
我正在尝试将此 json 格式的字符串转换为 GOLANG 中的实际 json 对象。
{"predictions": [{"predictions": [4492.0]}, {"predictions": [4515.84716796875]}, {"predictions": [4464.86083984375]}]}
基本上,它是一个带有键“预测”的字典,值是一个字典数组(每个字典都有一个键“预测”和一个 1 元素浮点数组的值。我创建了两个结构(一个对于第一个字典和另一个字典数组),但我无法将字符串 json 适合我的结构。我不确定我错过了什么
package main
import (
"encoding/json"
"fmt"
)
type dataPredictions struct {
SinglePredictions *SinglePredictions `json:"predictions"`
}
type SinglePredictions struct {
Predictions []map[string]int `json:predictions`
}
func main() {
s := `{"predictions": [{"predictions": [4492.0]}, {"predictions": [4515.84716796875]}, {"predictions": [4464.86083984375]}]}`
data := &dataPredictions{
SinglePredictions: &SinglePredictions{},
}
err := json.Unmarshal([]byte(s), data)
s2, _ := json.Marshal(data)
fmt.Println(err)
fmt.Println(data.SinglePredictions)
fmt.Println(string(s2))
}
我得到的错误如下。
json: cannot unmarshal array into Go struct field dataPredictions.predictions of type main.SinglePredictions
【问题讨论】:
-
请注意,您并没有将其解组为“JSON 对象”。原始字符串是一个 JSON 对象,您将其解组为 Go 结构。