I have created a webserver using the library net http. My problem is that I want to create a Struct like below from a JSON object, whose keys names don't match with the struct attributes.
type JsonData struct {
Operation string
IsStaff int
}
The JSON object sent from the server is:
{
"function": "search",
"is_staff": 1
"description": "Test"
}
Most of the solutions I have found are creating another struct, where the JSON keys and struct attribute names match each other. Is there a way to map the JSON decoded to my JsonData struct? Below it is my current function right now.
func handler(w http.ResponseWriter, r *http.Request){
switch r.Method {
case http.MethodPost:
var data JsonData
err := json.NewDecoder(r.Body).Decode(&data)
}
}
Search for "tag" in the json.Marshal
documentation.
Basically, you can tag struct fields with special annotations that tell the default un/marshaler to use the given name instead of the (case-insensitive) name of the struct field.
For your struct you can likely just do the following, depending on your actual intent:
type JsonData struct {
Operation string `json:"function"`
IsStaff int `json:"is_staff"`
}
func main() {
jsonstr := `{"function":"search","is_staff":1,"description":"Test"}`
var jd JsonData
err := json.Unmarshal([]byte(jsonstr), &jd)
fmt.Printf("OK: jd=%#v, err=%v
", jd, err)
// OK: jd=main.JsonData{Operation:"search", IsStaff:1}, err=<nil>
}