Go学习笔记-JSON处理

JSON是现代Web开发中最常用的数据交换格式。Go语言提供了强大的encoding/json包,支持JSON的编码、解码以及各种高级特性。

基本JSON操作

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package main

import (
    "encoding/json"
    "fmt"
    "log"
    "time"
)

// 1. 基本结构体
type Person struct {
    Name    string `json:"name"`
    Age     int    `json:"age"`
    Email   string `json:"email"`
    IsAdmin bool   `json:"is_admin"`
}

// 2. 嵌套结构体
type Address struct {
    Street  string `json:"street"`
    City    string `json:"city"`
    Country string `json:"country"`
    ZipCode string `json:"zip_code"`
}

type User struct {
    ID       int     `json:"id"`
    Name     string  `json:"name"`
    Email    string  `json:"email"`
    Address  Address `json:"address"`
    CreateAt string  `json:"created_at"`
}

// 3. 基本编码和解码
func basicJSONOperations() {
    fmt.Println("=== 基本JSON操作 ===")
    
    // 创建结构体实例
    person := Person{
        Name:    "张三",
        Age:     30,
        Email:   "zhangsan@example.com",
        IsAdmin: true,
    }
    
    // 编码为JSON
    jsonData, err := json.Marshal(person)
    if err != nil {
        log.Fatal("JSON编码失败:", err)
    }
    
    fmt.Printf("编码结果: %s\n", jsonData)
    
    // 解码JSON
    var decodedPerson Person
    err = json.Unmarshal(jsonData, &decodedPerson)
    if err != nil {
        log.Fatal("JSON解码失败:", err)
    }
    
    fmt.Printf("解码结果: %+v\n", decodedPerson)
}

// 4. 嵌套结构体JSON处理
func nestedStructJSON() {
    fmt.Println("\n=== 嵌套结构体JSON ===")
    
    user := User{
        ID:    1,
        Name:  "李四",
        Email: "lisi@example.com",
        Address: Address{
            Street:  "中关村大街1号",
            City:    "北京",
            Country: "中国",
            ZipCode: "100080",
        },
        CreateAt: time.Now().Format(time.RFC3339),
    }
    
    // 美化输出
    jsonData, err := json.MarshalIndent(user, "", "  ")
    if err != nil {
        log.Fatal("JSON编码失败:", err)
    }
    
    fmt.Printf("美化JSON:\n%s\n", jsonData)
    
    // 解码
    var decodedUser User
    err = json.Unmarshal(jsonData, &decodedUser)
    if err != nil {
        log.Fatal("JSON解码失败:", err)
    }
    
    fmt.Printf("解码用户: %+v\n", decodedUser)
    fmt.Printf("解码地址: %+v\n", decodedUser.Address)
}

// 5. 切片和映射的JSON处理
func sliceMapJSON() {
    fmt.Println("\n=== 切片和映射JSON ===")
    
    // 切片
    numbers := []int{1, 2, 3, 4, 5}
    numbersJSON, _ := json.Marshal(numbers)
    fmt.Printf("数字切片: %s\n", numbersJSON)
    
    people := []Person{
        {Name: "Alice", Age: 25, Email: "alice@example.com", IsAdmin: false},
        {Name: "Bob", Age: 30, Email: "bob@example.com", IsAdmin: true},
    }
    peopleJSON, _ := json.MarshalIndent(people, "", "  ")
    fmt.Printf("人员切片:\n%s\n", peopleJSON)
    
    // 映射
    userMap := map[string]interface{}{
        "name":     "Charlie",
        "age":      28,
        "email":    "charlie@example.com",
        "skills":   []string{"Go", "Python", "JavaScript"},
        "metadata": map[string]string{"department": "Engineering"},
    }
    
    mapJSON, _ := json.MarshalIndent(userMap, "", "  ")
    fmt.Printf("映射JSON:\n%s\n", mapJSON)
    
    // 解码到映射
    var decodedMap map[string]interface{}
    json.Unmarshal(mapJSON, &decodedMap)
    fmt.Printf("解码映射: %+v\n", decodedMap)
}

// 6. 基本类型JSON处理
func primitiveTypesJSON() {
    fmt.Println("\n=== 基本类型JSON ===")
    
    // 字符串
    str := "Hello, JSON!"
    strJSON, _ := json.Marshal(str)
    fmt.Printf("字符串: %s\n", strJSON)
    
    // 数字
    num := 42
    numJSON, _ := json.Marshal(num)
    fmt.Printf("数字: %s\n", numJSON)
    
    // 布尔值
    flag := true
    flagJSON, _ := json.Marshal(flag)
    fmt.Printf("布尔值: %s\n", flagJSON)
    
    // nil值
    var nilValue *string
    nilJSON, _ := json.Marshal(nilValue)
    fmt.Printf("nil值: %s\n", nilJSON)
    
    // 解码基本类型
    var decodedStr string
    json.Unmarshal(strJSON, &decodedStr)
    fmt.Printf("解码字符串: %s\n", decodedStr)
    
    var decodedNum int
    json.Unmarshal(numJSON, &decodedNum)
    fmt.Printf("解码数字: %d\n", decodedNum)
}

func main() {
    basicJSONOperations()
    nestedStructJSON()
    sliceMapJSON()
    primitiveTypesJSON()
}

JSON标签和高级特性

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package main

import (
    "encoding/json"
    "fmt"
    "log"
    "time"
)

// 1. JSON标签详解
type Product struct {
    ID          int     `json:"id"`
    Name        string  `json:"name"`
    Price       float64 `json:"price"`
    Description string  `json:"description,omitempty"` // 空值时忽略
    InStock     bool    `json:"in_stock"`
    Category    string  `json:"category"`
    Tags        []string `json:"tags,omitempty"`
    Metadata    map[string]string `json:"metadata,omitempty"`
    CreatedAt   time.Time `json:"created_at"`
    UpdatedAt   *time.Time `json:"updated_at,omitempty"` // 指针类型,可为nil
    Internal    string  `json:"-"` // 忽略此字段
}

// 2. 自定义JSON编码
type CustomTime struct {
    time.Time
}

func (ct CustomTime) MarshalJSON() ([]byte, error) {
    return json.Marshal(ct.Time.Format("2006-01-02 15:04:05"))
}

func (ct *CustomTime) UnmarshalJSON(data []byte) error {
    var timeStr string
    if err := json.Unmarshal(data, &timeStr); err != nil {
        return err
    }
    
    t, err := time.Parse("2006-01-02 15:04:05", timeStr)
    if err != nil {
        return err
    }
    
    ct.Time = t
    return nil
}

type Event struct {
    ID        int        `json:"id"`
    Name      string     `json:"name"`
    StartTime CustomTime `json:"start_time"`
    EndTime   CustomTime `json:"end_time"`
}

// 3. 接口类型的JSON处理
type Shape interface {
    Area() float64
    Type() string
}

type Circle struct {
    Radius float64 `json:"radius"`
}

func (c Circle) Area() float64 {
    return 3.14159 * c.Radius * c.Radius
}

func (c Circle) Type() string {
    return "circle"
}

type Rectangle struct {
    Width  float64 `json:"width"`
    Height float64 `json:"height"`
}

func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

func (r Rectangle) Type() string {
    return "rectangle"
}

// 包装器用于处理接口类型
type ShapeWrapper struct {
    Type string      `json:"type"`
    Data interface{} `json:"data"`
}

// 4. JSON标签示例
func jsonTagsExample() {
    fmt.Println("=== JSON标签示例 ===")
    
    now := time.Now()
    product := Product{
        ID:          1,
        Name:        "Go编程书籍",
        Price:       89.99,
        Description: "", // 空字符串,会被omitempty忽略
        InStock:     true,
        Category:    "Books",
        Tags:        []string{"programming", "go", "tech"},
        Metadata: map[string]string{
            "author":    "Go Team",
            "publisher": "Tech Press",
        },
        CreatedAt: now,
        UpdatedAt: &now,
        Internal:  "这个字段不会出现在JSON中",
    }
    
    jsonData, err := json.MarshalIndent(product, "", "  ")
    if err != nil {
        log.Fatal("JSON编码失败:", err)
    }
    
    fmt.Printf("产品JSON:\n%s\n", jsonData)
    
    // 测试omitempty
    emptyProduct := Product{
        ID:       2,
        Name:     "空产品",
        Price:    0,
        InStock:  false,
        Category: "Test",
        CreatedAt: now,
    }
    
    emptyJSON, _ := json.MarshalIndent(emptyProduct, "", "  ")
    fmt.Printf("空产品JSON (注意omitempty效果):\n%s\n", emptyJSON)
}

// 5. 自定义JSON编码示例
func customJSONExample() {
    fmt.Println("\n=== 自定义JSON编码 ===")
    
    event := Event{
        ID:   1,
        Name: "Go会议",
        StartTime: CustomTime{time.Date(2024, 3, 15, 9, 0, 0, 0, time.UTC)},
        EndTime:   CustomTime{time.Date(2024, 3, 15, 17, 0, 0, 0, time.UTC)},
    }
    
    jsonData, err := json.MarshalIndent(event, "", "  ")
    if err != nil {
        log.Fatal("JSON编码失败:", err)
    }
    
    fmt.Printf("事件JSON:\n%s\n", jsonData)
    
    // 解码
    var decodedEvent Event
    err = json.Unmarshal(jsonData, &decodedEvent)
    if err != nil {
        log.Fatal("JSON解码失败:", err)
    }
    
    fmt.Printf("解码事件: %+v\n", decodedEvent)
    fmt.Printf("开始时间: %s\n", decodedEvent.StartTime.Format("2006-01-02 15:04:05"))
}

// 6. 接口类型JSON处理
func interfaceJSONExample() {
    fmt.Println("\n=== 接口类型JSON处理 ===")
    
    shapes := []Shape{
        Circle{Radius: 5},
        Rectangle{Width: 10, Height: 8},
    }
    
    // 包装接口类型
    var wrappers []ShapeWrapper
    for _, shape := range shapes {
        wrapper := ShapeWrapper{
            Type: shape.Type(),
            Data: shape,
        }
        wrappers = append(wrappers, wrapper)
    }
    
    jsonData, err := json.MarshalIndent(wrappers, "", "  ")
    if err != nil {
        log.Fatal("JSON编码失败:", err)
    }
    
    fmt.Printf("形状JSON:\n%s\n", jsonData)
    
    // 解码时需要根据类型进行处理
    var decodedWrappers []ShapeWrapper
    err = json.Unmarshal(jsonData, &decodedWrappers)
    if err != nil {
        log.Fatal("JSON解码失败:", err)
    }
    
    for _, wrapper := range decodedWrappers {
        fmt.Printf("类型: %s, 数据: %+v\n", wrapper.Type, wrapper.Data)
    }
}

// 7. 动态JSON处理
func dynamicJSONExample() {
    fmt.Println("\n=== 动态JSON处理 ===")
    
    // 未知结构的JSON
    jsonStr := `{
        "user": {
            "id": 123,
            "name": "John Doe",
            "email": "john@example.com",
            "preferences": {
                "theme": "dark",
                "language": "en"
            },
            "tags": ["developer", "golang", "json"]
        },
        "timestamp": "2024-03-15T10:30:00Z",
        "version": "1.0"
    }`
    
    // 解码到interface{}
    var data interface{}
    err := json.Unmarshal([]byte(jsonStr), &data)
    if err != nil {
        log.Fatal("JSON解码失败:", err)
    }
    
    // 类型断言访问数据
    if obj, ok := data.(map[string]interface{}); ok {
        if user, ok := obj["user"].(map[string]interface{}); ok {
            fmt.Printf("用户ID: %.0f\n", user["id"].(float64))
            fmt.Printf("用户名: %s\n", user["name"].(string))
            
            if prefs, ok := user["preferences"].(map[string]interface{}); ok {
                fmt.Printf("主题: %s\n", prefs["theme"].(string))
            }
            
            if tags, ok := user["tags"].([]interface{}); ok {
                fmt.Print("标签: ")
                for _, tag := range tags {
                    fmt.Printf("%s ", tag.(string))
                }
                fmt.Println()
            }
        }
        
        fmt.Printf("时间戳: %s\n", obj["timestamp"].(string))
        fmt.Printf("版本: %s\n", obj["version"].(string))
    }
}

func main() {
    jsonTagsExample()
    customJSONExample()
    interfaceJSONExample()
    dynamicJSONExample()
}

JSON流处理和性能优化

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package main

import (
    "encoding/json"
    "fmt"
    "io"
    "log"
    "strings"
    "time"
)

// 1. JSON流处理
type LogEntry struct {
    Timestamp time.Time `json:"timestamp"`
    Level     string    `json:"level"`
    Message   string    `json:"message"`
    Source    string    `json:"source"`
}

// 2. 流式编码
func streamEncoding() {
    fmt.Println("=== 流式编码 ===")
    
    var output strings.Builder
    encoder := json.NewEncoder(&output)
    
    // 设置缩进
    encoder.SetIndent("", "  ")
    
    logs := []LogEntry{
        {
            Timestamp: time.Now(),
            Level:     "INFO",
            Message:   "应用程序启动",
            Source:    "main.go",
        },
        {
            Timestamp: time.Now().Add(time.Second),
            Level:     "DEBUG",
            Message:   "处理用户请求",
            Source:    "handler.go",
        },
        {
            Timestamp: time.Now().Add(2 * time.Second),
            Level:     "ERROR",
            Message:   "数据库连接失败",
            Source:    "db.go",
        },
    }
    
    // 逐个编码
    for _, entry := range logs {
        if err := encoder.Encode(entry); err != nil {
            log.Fatal("编码失败:", err)
        }
    }
    
    fmt.Printf("流式编码结果:\n%s", output.String())
}

// 3. 流式解码
func streamDecoding() {
    fmt.Println("\n=== 流式解码 ===")
    
    // 模拟JSON流数据
    jsonStream := `
    {"timestamp":"2024-03-15T10:00:00Z","level":"INFO","message":"服务启动","source":"main.go"}
    {"timestamp":"2024-03-15T10:01:00Z","level":"DEBUG","message":"用户登录","source":"auth.go"}
    {"timestamp":"2024-03-15T10:02:00Z","level":"WARN","message":"内存使用率高","source":"monitor.go"}
    {"timestamp":"2024-03-15T10:03:00Z","level":"ERROR","message":"请求超时","source":"api.go"}
    `
    
    reader := strings.NewReader(jsonStream)
    decoder := json.NewDecoder(reader)
    
    var count int
    for {
        var entry LogEntry
        if err := decoder.Decode(&entry); err == io.EOF {
            break
        } else if err != nil {
            log.Fatal("解码失败:", err)
        }
        
        count++
        fmt.Printf("日志 %d: [%s] %s - %s (%s)\n", 
            count, entry.Level, entry.Timestamp.Format("15:04:05"), 
            entry.Message, entry.Source)
    }
}

// 4. 大型JSON处理
func largeJSONProcessing() {
    fmt.Println("\n=== 大型JSON处理 ===")
    
    // 创建大量数据
    var users []map[string]interface{}
    for i := 1; i <= 10000; i++ {
        user := map[string]interface{}{
            "id":       i,
            "name":     fmt.Sprintf("User%d", i),
            "email":    fmt.Sprintf("user%d@example.com", i),
            "active":   i%2 == 0,
            "score":    float64(i * 10),
            "metadata": map[string]string{"group": fmt.Sprintf("group%d", i%10)},
        }
        users = append(users, user)
    }
    
    // 测试编码性能
    start := time.Now()
    jsonData, err := json.Marshal(users)
    if err != nil {
        log.Fatal("编码失败:", err)
    }
    encodeTime := time.Since(start)
    
    fmt.Printf("编码 %d 个用户耗时: %v\n", len(users), encodeTime)
    fmt.Printf("JSON大小: %d 字节\n", len(jsonData))
    
    // 测试解码性能
    start = time.Now()
    var decodedUsers []map[string]interface{}
    err = json.Unmarshal(jsonData, &decodedUsers)
    if err != nil {
        log.Fatal("解码失败:", err)
    }
    decodeTime := time.Since(start)
    
    fmt.Printf("解码 %d 个用户耗时: %v\n", len(decodedUsers), decodeTime)
}

// 5. JSON验证和错误处理
func jsonValidationAndErrors() {
    fmt.Println("\n=== JSON验证和错误处理 ===")
    
    // 有效JSON
    validJSON := `{"name": "Alice", "age": 30, "email": "alice@example.com"}`
    
    // 无效JSON示例
    invalidJSONs := []string{
        `{"name": "Bob", "age": 25, "email": }`, // 缺少值
        `{"name": "Charlie", "age": "thirty"}`,   // 类型错误
        `{"name": "David", "age": 35`,            // 缺少结束括号
        `{name: "Eve", "age": 28}`,               // 键没有引号
    }
    
    // 验证有效JSON
    var person map[string]interface{}
    if err := json.Unmarshal([]byte(validJSON), &person); err != nil {
        fmt.Printf("有效JSON解析失败: %v\n", err)
    } else {
        fmt.Printf("有效JSON解析成功: %+v\n", person)
    }
    
    // 验证无效JSON
    for i, invalidJSON := range invalidJSONs {
        var data map[string]interface{}
        if err := json.Unmarshal([]byte(invalidJSON), &data); err != nil {
            fmt.Printf("无效JSON %d 错误: %v\n", i+1, err)
        } else {
            fmt.Printf("无效JSON %d 意外成功: %+v\n", i+1, data)
        }
    }
}

// 6. JSON性能优化技巧
func jsonPerformanceOptimization() {
    fmt.Println("\n=== JSON性能优化 ===")
    
    // 1. 预分配切片容量
    start := time.Now()
    var items1 []map[string]interface{}
    for i := 0; i < 10000; i++ {
        item := map[string]interface{}{"id": i, "value": fmt.Sprintf("item%d", i)}
        items1 = append(items1, item)
    }
    time1 := time.Since(start)
    
    start = time.Now()
    items2 := make([]map[string]interface{}, 0, 10000) // 预分配容量
    for i := 0; i < 10000; i++ {
        item := map[string]interface{}{"id": i, "value": fmt.Sprintf("item%d", i)}
        items2 = append(items2, item)
    }
    time2 := time.Since(start)
    
    fmt.Printf("不预分配容量: %v\n", time1)
    fmt.Printf("预分配容量: %v\n", time2)
    fmt.Printf("性能提升: %.2fx\n", float64(time1)/float64(time2))
    
    // 2. 重用编码器/解码器
    var output strings.Builder
    encoder := json.NewEncoder(&output)
    
    start = time.Now()
    for i := 0; i < 1000; i++ {
        item := map[string]interface{}{"id": i}
        encoder.Encode(item)
    }
    reuseTime := time.Since(start)
    
    start = time.Now()
    for i := 0; i < 1000; i++ {
        item := map[string]interface{}{"id": i}
        json.Marshal(item) // 每次创建新的编码器
    }
    newTime := time.Since(start)
    
    fmt.Printf("重用编码器: %v\n", reuseTime)
    fmt.Printf("每次新建: %v\n", newTime)
    fmt.Printf("重用性能提升: %.2fx\n", float64(newTime)/float64(reuseTime))
}

// 7. 自定义JSON字段名映射
type APIResponse struct {
    Status  string      `json:"status"`
    Data    interface{} `json:"data"`
    Message string      `json:"message,omitempty"`
    Error   string      `json:"error,omitempty"`
}

func customFieldMapping() {
    fmt.Println("\n=== 自定义字段映射 ===")
    
    // 成功响应
    successResp := APIResponse{
        Status: "success",
        Data: map[string]interface{}{
            "users": []map[string]interface{}{
                {"id": 1, "name": "Alice"},
                {"id": 2, "name": "Bob"},
            },
            "total": 2,
        },
        Message: "用户列表获取成功",
    }
    
    successJSON, _ := json.MarshalIndent(successResp, "", "  ")
    fmt.Printf("成功响应:\n%s\n", successJSON)
    
    // 错误响应
    errorResp := APIResponse{
        Status: "error",
        Error:  "用户不存在",
    }
    
    errorJSON, _ := json.MarshalIndent(errorResp, "", "  ")
    fmt.Printf("错误响应:\n%s\n", errorJSON)
}

func main() {
    streamEncoding()
    streamDecoding()
    largeJSONProcessing()
    jsonValidationAndErrors()
    jsonPerformanceOptimization()
    customFieldMapping()
}

总结

  1. 基本操作

    • json.Marshal() - 编码为JSON
    • json.Unmarshal() - 从JSON解码
    • json.MarshalIndent() - 美化输出
    • 支持结构体、切片、映射等类型
  2. JSON标签

    • json:"name" - 自定义字段名
    • json:",omitempty" - 空值时忽略
    • json:"-" - 忽略字段
    • 标签控制序列化行为
  3. 高级特性

    • 自定义MarshalJSONUnmarshalJSON方法
    • 接口类型的JSON处理
    • 动态JSON处理
    • 流式编码和解码
  4. 性能优化

    • 预分配切片容量
    • 重用编码器/解码器
    • 避免不必要的类型转换
    • 合理使用流式处理
  5. 最佳实践

    • 使用结构体标签控制JSON格式
    • 处理JSON解析错误
    • 验证JSON数据的有效性
    • 考虑大型JSON的内存使用
    • 使用适当的数据类型
updatedupdated2025-09-202025-09-20