Trung BìnhGolang iconGolang

JSON encode/decode trong Go thế nào?

Go sử dụng package encoding/json.

Struct tags quyết định cách ánh xạ field sang JSON key.

go
// Định nghĩa struct với JSON tags
type User struct {
    Name  string `json:"name"`
    Age   int    `json:"age,omitempty"` // bỏ qua nếu zero value
    Email string `json:"-"`             // luôn bỏ qua khi encode
}

// Marshal — struct → JSON bytes
u := User{Name: "Alice", Age: 30}
data, err := json.Marshal(u)
// {"name":"Alice","age":30}

// Unmarshal — JSON bytes → struct
var u2 User
err = json.Unmarshal(data, &u2)

// HTTP response — dùng Encoder để stream
func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(User{Name: "Bob", Age: 25})
}

// HTTP request body — dùng Decoder
func createUser(w http.ResponseWriter, r *http.Request) {
    var u User
    if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
}

Xem toàn bộ Golang cùng filter theo level & chủ đề con.

Mở danh sách Golang