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\n", p.firstName)
}
Done!