golang encoding/json
1 package main 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 ) 8 9 type ColorGroup struct { 10 ID int 11 Name string 12 Colors []string 13 } 14 15 func main() { 16 17 //---------------Marshal 18 group := ColorGroup{ 19 ID: 1, 20 Name: "Reds", 21 Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, 22 } 23 b, err := json.Marshal(group) 24 if err != nil { 25 fmt.Println("error:", err) 26 } 27 //os.Stdout.Write(b) 28 fmt.Println(string(b[:])) 29 30 //---------------Unmarshal 31 var jsonBlob = []byte(`[ 32 {"ID":1,"Name":"Reds1","Colors":["Crimson","Red1","Ruby1","Maroon1"]}, 33 {"ID":2,"Name":"Reds2","Colors":["Crimson","Red2","Ruby2","Maroon2"]}, 34 {"ID":3,"Name":"Reds3","Colors":["Crimson","Red3","Ruby3","Maroon3"]} 35 ]`) 36 37 var animals []ColorGroup 38 error := json.Unmarshal(jsonBlob, &animals) 39 if error != nil { 40 fmt.Println("error:", error) 41 } 42 43 //fmt.Printf("%+v", animals) 44 //fmt.Println(animals) 45 for i, x := range animals { 46 fmt.Println(i, x) 47 48 } 49 //---------------Indent 50 dst := new(bytes.Buffer) 51 json.Indent(dst, jsonBlob, "##", "**") 52 fmt.Println(dst) 53 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何在 .NET 中 使用 ANTLR4
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 想让你多爱自己一些的开源计时器
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析