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 關注
- 162 瀏覽
添加回答
舉報