Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang: struct does not unmarshal int64 field correctly, other fields are correct

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading