您好,登錄后才能下訂單哦!
這篇文章主要介紹“Go語言怎么利用Unmarshal解析json字符串”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Go語言怎么利用Unmarshal解析json字符串”文章能幫助大家解決問題。
簡單的解析例子:
首先還是從官方文檔中的例子:
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("%+v\n", fruitGroup) fmt.Printf("%+v\n", fruitGroup.FirstFruit) fmt.Printf("%+v\n", 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字符串”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。