I have following code which is ok, it will print Bob
:
package main
import (
"encoding/json"
"fmt"
)
type User struct {
UserName string // line2
Age int
}
func main() {
var u User
str := `{"userName":"Bob", "age": 20}` // line1
json.Unmarshal([]byte(str), &u)
fmt.Println(u.UserName)
}
Unfortunately, in real case, the json string in line1
is next, which you could see there is a hyphen(-
) in the key.
str := `{"user-Name":"Bob", "age": 20}`
And as you all know, to automatically unmarshal the json string, we have to define a member in struct which is the same name of the key in json string, of course need to make it upper case. So I tried to change line2
to User-Name string
, but -
is not valid in go
variable name. What should I do?