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
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.