I use jquery to send ajax json data for golang web restful service. And want to parse the json data in my backend using golang. Here is simple javascript code:
$.ajax({
url: "http://localhost:8080/persons",
type: "POST",
dataType: "json",
data: {
"data": '{"firstName": "Hello","lastName": "World"}'
},
success:function (res) {
console.log(res)
},
error: function (err){
console.log(err)
}
})
Then use GetRawData() to get the gin.Context information, and a json decoder to parse the json content,
data, _ := c.GetRawData()
jsonStream := string(data)
dec := json.NewDecoder(strings.NewReader(jsonStream))
t, err := dec.Token()
if err != nil {
log.Fatal(err)
}
for dec.More() {
var p Person
err := dec.Decode(&p)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Hello %s
", p.firstName)
}
Done!
I'm not very familiar with Gin, but to accept application/json
data, use gin.Context.BindJSON
to bind the values in the request.
router.POST("/persons", func(c *gin.Context) {
var jsonData Member
if c.BindJSON(&jsonData) == nil {
fmt.Println(jsonData.first_name + " " + jsonData.last_name)
} else {
// handle error
}
}
Updating with Peter's suggestion for exporting the fields:
type Person struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
}