Lab 11: JSON Encoding
Overview
Step 1: Marshal — Struct to JSON
package main
import (
"encoding/json"
"fmt"
"time"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"` // omit if empty
CreatedAt time.Time `json:"created_at"`
Password string `json:"-"` // never marshal
}
func main() {
u := User{
ID: 1,
Name: "Alice",
CreatedAt: time.Date(2024, 1, 15, 0, 0, 0, 0, time.UTC),
Password: "secret", // will not appear in JSON
}
b, err := json.MarshalIndent(u, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(b))
}Step 2: Unmarshal — JSON to Struct
Step 3: Custom MarshalJSON / UnmarshalJSON
Step 4: Streaming with json.Encoder / json.Decoder
Step 5: json.RawMessage — Deferred Parsing
Step 6: json.Number for Precise Numbers
Step 7: Map and Slice JSON
Step 8: Capstone — JSON API Response Builder
Summary
Feature
Struct Tag / API
Notes
Last updated
