CodeFun Go

Marshal与Unmarshal实例解析

encoding/json包提供了Marshal与Unmarshal函数,可用于将 golang 数组、切片、映射、结构体转换为 JSON 字符串,反之亦然。

package main

import (
    "fmt"
    "encoding/json"
)

type Example struct {
    Page   int      `json:"page"`
    Fruits []string `json:"fruits"`
}

func main() {
    // slice/array to json
    s := []string{"apple", "peach", "pear"}
    slcB, _ := json.Marshal(s)
    fmt.Println(string(slcB))
    //map to json
    m := map[string]int{"apple": 5, "lettuce": 7}
    mapB, _ := json.Marshal(m)
    fmt.Println(string(mapB))
    // struct to json
    stru := Example{
        Page:   1,
        Fruits: s}
    struB, _ := json.Marshal(stru)
    fmt.Println(string(struB))

    // json to slice/array
    s1 := make([]string, 0)
    if err := json.Unmarshal(slcB, &s1); err != nil {
        panic(err)
    }
    fmt.Printf("type: %T, content: %v\n", s1, s1)
    // json to map
    m1 := make(map[string]int, 0)
    if err := json.Unmarshal(mapB, &m1); err != nil {
        panic(err)
    }
    fmt.Printf("type: %T, content: %v\n", m1, m1)
    // json to struct
    stru1 := Example{}
    if err := json.Unmarshal(struB, &stru1); err != nil {
        panic(err)
    }
    fmt.Printf("type: %T, content: %v\n", stru1, stru1)
}
["apple","peach","pear"]
{"apple":5,"lettuce":7}
{"page":1,"fruits":["apple","peach","pear"]}
type: []string, content: [apple peach pear]
type: map[string]int, content: map[apple:5 lettuce:7]
type: main.Example, content: {1 [apple peach pear]}