Skip to content

练习 — JSON ​

对应知识点:JSON 对应文档:docs/phase-02-core/json.md 代码目录:workspace/phase-02/json/

前置条件:掌握 struct、tag、error handling。


Level 1 — 基础 ​

练习 1.1 · Marshal AGVState ​

新建 workspace/phase-02/json/main.go。

要求:

  • 定义 AGVState struct,字段 id/x/y/speed/battery/online,json tag 用 camelCase
  • 创建示例数据,Marshal 并打印 JSON 字符串

练习 1.2 · Unmarshal ​

要求:

  • JSON 字符串:'{"id":"AGV-002","x":0,"y":0,"battery":50,"online":false}'
  • Unmarshal 到 AGVState,打印各字段
  • 处理 Unmarshal error

练习 1.3 · 未导出字段 ​

要求:

  • struct 含小写字段 internal string 和大写字段 ID string
  • Marshal 后确认小写字段未出现在 JSON 中

Level 2 — 应用 ​

练习 2.1 · omitempty ​

要求:

  • Speed 字段 tag 加 omitempty
  • 分别 Marshal Speed=0 和 Speed=1.2 两种情况
  • 对比 JSON 输出差异,理解零值省略

练习 2.2 · map[string]any ​

要求:

  • Unmarshal 到 map[string]any
  • 读取 id 和 battery 字段(注意类型断言)
  • 打印类型:fmt.Printf("%T\n", raw["battery"])

练习 2.3 · SensorReading ​

要求:

  • 定义 SensorReading:deviceId、timestamp(int64)、value(float64)、unit(string)
  • 双向测试 Marshal / Unmarshal
  • timestamp 使用 Unix 毫秒

Level 3 — 综合 ​

练习 3.1 · 设备数组 ​

要求:

  • 定义 []AGVState 含 3 台设备
  • Marshal 为 JSON 数组
  • 从 JSON 数组 Unmarshal 回 slice,验证长度和内容

练习 3.2 · 多态消息 RawMessage ​

要求:

  • 定义 Message struct:Type string、Payload json.RawMessage
  • Type 为 "agv" 时 Payload 解析为 AGVState
  • Type 为 "sensor" 时 Payload 解析为 SensorReading
  • main 演示两种消息

Level 4 — 项目实践 ​

练习 4.1 · Twin Message 模块 ​

在 workspace/phase-02/json/ 完成:

文件:

  • models.go:AGVState、SensorReading、TwinUpdate(type/deviceId/timestamp/payload)
  • codec.go:EncodeUpdate(u TwinUpdate) ([]byte, error)、DecodeUpdate(data []byte) (TwinUpdate, error)
  • main.go:模拟 HTTP Body 读写(bytes.NewReader / bytes.Buffer)

要求:

  • 字段名与 Vue 前端 camelCase 一致
  • 完整 error handling
  • 打印 pretty JSON(MarshalIndent)

学习检查 ​

  • [ ] Unmarshal 第二个参数为什么必须是指针?
  • [ ] omitempty 和 - tag 的区别?
  • [ ] JSON 数字 Unmarshal 到 any 是什么类型?
  • [ ] 如何匹配 Vue 前端的 camelCase?
  • [ ] Marshal 和 Encoder 的使用场景?

提交方式 ​

检查答案 — JSON 练习 X.X

学习导航 ​

上一篇:Go Error Handling · 对应知识文档 · 下一篇:Go Package Design