Go has a built-in encoding/json
package that can easily parse json strings into structures, or parse structures into json strings.
Convert json string to structure:
json.NewDecoder(r.Body).Decode(&user)
Structure to json string:
json.NewEncoder(w).Encode(peter)
By adding after the structure field
`json:“xxx” `
In order to convert the field into a specific json field, otherwise it will be output as the original field.
Full code:
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type User struct {
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
Age int `json:"age"`
}
func main() {
http.HandleFunc("/decode", func(w http.ResponseWriter, r *http.Request) {
var user User
json.NewDecoder(r.Body).Decode(&user)
fmt.Fprintf(w, "%s %s is %d years old!", user.Firstname, user.Lastname, user.Age)
})
http.HandleFunc("/encode", func(w http.ResponseWriter, r *http.Request) {
peter := User{
Firstname: "John",
Lastname: "Doe",
Age: 25,
}
json.NewEncoder(w).Encode(peter)
})
http.ListenAndServe(":8080", nil)
}
verify:
visit/decode | visit /encode |
---|---|