I have an http endpoint that receives some json that I unmarshal into a struct. All fields unmarshal correctly with the exception of an int64 timestamp field. There is no error, but the value is set to 0 instead of the value in the json. I tried changing to an int but got the same result.
The struct definition:
type BTMeta struct {
IMEI string `json: "imei"`
Timestamp int64 `json: "ts"`
SignalStrength int `json: "signalStrength"`
BatteryVoltage int `json: "batteryVoltage"`
}
type BTWeightValues struct {
Unit int `json: "unit"`
Tare int `json: "tare"`
Weight uint `json: "weight"`
}
type BTWeight struct {
BTMeta
Values BTWeightValues `json: "values"`
}
The controller code (I removed error checking and irrelevant code):
func PostBTScale(res http.ResponseWriter, req *http.Request) {
var data model.BTWeight
_ := json.NewDecoder(req.Body).Decode(&data)
log.Println(data.Timestamp)
_ = database.DB.AddNewWeight(data)
res.WriteHeader(http.StatusOK)
}
The JSON:
{
"imei": "012896009462125",
"ts": 1380562575798,
"batteryVoltage": 5940,
"signalStrength": 90,
"values": {
"unit": 1,
"tare": 0,
"weight": 61200
},
"rssi": 68,
"deviceId": 12896009462125
}
Everything is correct after I unmarshal into a BTWeight except Timestamp is set to 0.
CodePudding user response:
None of the JSON tags are working. The correct form of json tags are:
Timestamp int64 `json:"ts"`
Not
Timestamp int64 `json: "ts"`
That is, without the space after :
.
It is working for other fields because field names match JSON keys.