CodeFun Go

JSON与结构体相互解析

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

结构体转json

jsonBytes, error := json.Marshal(struct)

json转结构体

err := json.Unmarshal(jsonBytes, &struct);
package main

import (
    "fmt"
    "encoding/json"
)

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

func main() {
    // struct to json
    stru := Example{
        Page:   1,
        Fruits: []string{"apple", "peach", "pear"}}
    struB, _ := json.Marshal(stru)
    fmt.Println(string(struB))

    // json to struct
    stru1 := Example{}
    if err := json.Unmarshal(struB, &stru1); err != nil {
        panic(err)
    }
    fmt.Printf("type: %T, content: %v\n", stru1, stru1)
}
{"page":1,"fruits":["apple","peach","pear"]}
type: main.Example, content: {1 [apple peach pear]}