1 回答

TA贡献1868条经验 获得超4个赞
如果您检查 的源代码json.Decoder,
...
type Decoder struct {
r io.Reader
buf []byte
d decodeState
scanp int // start of unread data in buf
scan scanner
err error
tokenState int
tokenStack []int
}
func NewDecoder(r io.Reader) *Decoder {
return &Decoder{r: r}
}
...
您可以看到NewDecoder仅设置r字段,这就是您在fmt.Printf.
在您执行之前err := decoder.Decode(&apdata),您的结构不会被填充。您在输出中看到的是解码器的内容,而不是正文或您的结构。
如果在运行后打印结构err := decoder.Decode(&apdata),它包含正确的数据:
package main
import (
"fmt"
"encoding/json"
"strings"
)
func main() {
input := `{
"mac":"01:0a:95:9d:68:20",
"rssi_max":-73.50,
"rssi_min":-50.02,
"loc_def_id":1
}`
decoder := json.NewDecoder(strings.NewReader(input))
var apdata struct {
ID int `db:"id"`
Mac string `json:"mac" db:"mac"`
RssiMax uint64 `json:"rssi_max" db:"rssi_max"`
RssiMin uint16 `json:"rssi_min" db:"rssi_min"`
LocDefId uint64 `json:"loc_def_id" db:"loc_def_id"`
}
_ = decoder.Decode(&apdata)
fmt.Printf("appdata : %+v\n", apdata)
}
输出:
appdata : {ID:0 Mac:01:0a:95:9d:68:20 RssiMax:0 RssiMin:0 LocDefId:1}
的RssiMax和RssiMin是零,因为他们接受负值无符号整数。
- 1 回答
- 0 关注
- 137 浏览
添加回答
举报