Custom struct filed tags

type Device_Config struct {
Volume int `json:"vol,omitempty"`
LED bool `json:"led_en,omitempty"`
}

For the above struct , after I unMarshal it the values are correctly populated in the resulting struct Device_Config when the json received is say in the format below [using fiddler to test this]

{"led_en":true,"vol":3}

The same would not work if the request body is as below

{"LED":true,"Volume":3}

var dat Device_Config
err := json.Unmarshal([]byte(body), &dat)

The type of ‘body’ is 'string’
The resulting struct ‘dat’ would have the default values, as though the ‘json.Unmarshal’ didnot work.
Any leads to the problem would be useful. Thanks

If you set the json struct tags then those are the expected field names. If the field names vary like this you can use several structs or a map.

Erh, also the types in your second example are wrong. I have no idea what you expected that to deserialize to? What did you expect / want to happen?

JSON is case sensitive.

If you want to treat "volume" and "Volume" the same keys, you need to write a custom marshaller.

It’s a lot more than just a case difference though, or we could make do by scrapping the struct tags.

Sorry ,my bad. I corrected the example code.But ideally when i do a POST operation with the request body, shouldn’t I be allowed with either the filed name like ‘Volume’ or json tag name ‘vol’. I expect to see same result with either used in request body. Please correct if i am wrong.

In the Go JSON unmarshaller sense, you are wrong. If you set the struct tag, that’s the only accepted JSON key. If you don’t set it, it’ll accept case variations on the field name.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.