概述
简单的解析例子:
首先还是从官方文档中的例子:
package main import ( "fmt" "encoding/json" ) type Animal struct { Name string Order string } func main() { var jsonBlob = []byte(`[ {"Name": "Platypus", "Order": "Monotremata"}, {"Name": "Quoll", "Order": "Dasyuromorphia"} ]`) var animals []Animal err := json.Unmarshal(jsonBlob, &animals) if err != nil { fmt.Println("error:", err) } fmt.Printf("%+v", animals) }
输出:
[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
简单进行修改,修改为:
package main import ( "fmt" "encoding/json" ) type Animal struct { Name string Order string } func main() { var jsonBlob = []byte(`{"Name": "Platypus", "Order": "Monotremata"}`) var animals Animal err := json.Unmarshal(jsonBlob, &animals) if err != nil { fmt.Println("error:", err) } fmt.Printf("%+v", animals) }
输出:
{Name:Platypus Order:Monotremata}
还是之前的例子:
解析这样的一个json字符串:
{ "first fruit": { "describe":"an apple", "icon":"appleIcon", "name":"apple" }, "second fruit": { "describe":"an orange", "icon":"orangeIcon", "name":"orange" }, "three fruit array": [ "eat 0", "eat 1", "eat 2", "eat 3", "eat 4" ] }
go代码:
package main import ( "fmt" "encoding/json" ) type Fruit struct { Describe string `json:"describe"` Icon string `json:"icon"` Name string `json:"name"` } type FruitGroup struct { FirstFruit *Fruit `json:"first fruit"` //指针,指向引用对象;如果不用指针,只是值复制 SecondFruit *Fruit `json:"second fruit"` //指针,指向引用对象;如果不用指针,只是值复制 THreeFruitArray []string `json:"three fruit array"` } func main() { var jsonBlob = []byte(`{ "first fruit": { "describe": "an apple", "icon": "appleIcon", "name": "apple" }, "second fruit": { "describe": "an orange", "icon": "appleIcon", "name": "orange" }, "three fruit array": [ "eat 0", "eat 1", "eat 2", "eat 3" ]}`) var fruitGroup FruitGroup err := json.Unmarshal(jsonBlob, &fruitGroup) if err != nil { fmt.Println("error:", err) } fmt.Printf("%+vn", fruitGroup) fmt.Printf("%+vn", fruitGroup.FirstFruit) fmt.Printf("%+vn", fruitGroup.SecondFruit) }
运行结果:
{FirstFruit:0xc00006c5a0 SecondFruit:0xc00006c5d0 THreeFruitArray:[eat 0 eat 1 eat 2 eat 3]}
&{Describe:an apple Icon:appleIcon Name:apple}
&{Describe:an orange Icon:appleIcon Name:orange}
到此这篇关于Go语言利用Unmarshal解析json字符串的实现的文章就介绍到这了,更多相关Go Unmarshal解析json字符串内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!
最后
以上就是兴奋溪流为你收集整理的Go语言利用Unmarshal解析json字符串的实现的全部内容,希望文章能够帮你解决Go语言利用Unmarshal解析json字符串的实现所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复