MENU

Go 学习笔记:Json转换

September 9, 2021 • Read: 233 • Golang

Go 语言是不能像JavaScript一样直接支持Json这种类型的,需要自己手动将Json转换为Go语言能支持的数据结构

Json转换为map

如果json内的字段是确定的,你可以这样写

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-09-05 18:36:02
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    str := `{"name":"dio", "age":"12"}`
    dict := make(map[string]string)
    err := json.Unmarshal([]byte(str), &dict)
    if err != nil {
        fmt.Println("ERR:", err)
    } else {
        fmt.Println(dict)
    }
}

如果不能确定,那就用interface来替代即可

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-09-05 18:39:55
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    str := `{"name":"dio", "age":12}`
    dict := make(map[string]interface{})
    err := json.Unmarshal([]byte(str), &dict)
    if err != nil {
        fmt.Println("ERR:", err)
    } else {
        // fmt.Println(dict["age"])
        fmt.Printf("%T\n", dict["age"])
    }
}

Json转换为切片

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-09-05 18:44:53
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    str := `["name", "value"]`
    dict := make([]string, 32)
    err := json.Unmarshal([]byte(str), &dict)
    if err != nil {
        fmt.Println("ERR:", err)
    } else {
        fmt.Println(dict[0])
        fmt.Printf("%T\n", dict)
    }
}

Json转结构体

Json转结构体的时候,需要先声明结构体

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-09-05 18:50:37
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "encoding/json"
    "fmt"
)

type Dict struct {
    name  string
    age   int32
    bobby []string
}

func main() {
    str := `{"name": "dio", "age":12, "hobby":["Programming", "dancing"]}`
    dict := Dict{}
    err := json.Unmarshal([]byte(str), &dict)
    if err != nil {
        fmt.Println("ERR:", err)
    } else {
        fmt.Printf("%+v\n", dict)
        fmt.Printf("%T\n", dict)
    }
}
Archives Tip
QR Code for this page
Tipping QR Code