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字符串的實現的文章就介紹到這瞭,更多相關Go Unmarshal解析json字符串內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: