json与数据结构

cooolr 于 2021-04-12 发布

编码解码

package main

import "fmt"
import "encoding/json"

type Data struct {
    Type string `json:"type"`
    Text string `json:"text"`
}

func main(){
    text,_ := json.Marshal("hello world")
    var _text string
    _ = json.Unmarshal([]byte(string(text)), &_text)
    fmt.Println("字符串json编码:", string(text))
    fmt.Println("字符串json解码:", _text)

    slice,_ := json.Marshal([]int{1, 2, 3, 4, 5})
    var _slice []int
    _ = json.Unmarshal([]byte(string(slice)), &_slice)
    fmt.Println("切片json编码:", string(slice))
    fmt.Println("切片json解码:", _slice)

    structD,_ := json.Marshal(Data{"Toast", "Hello World"})
    var _structD Data
    _ = json.Unmarshal([]byte(string(structD)), &_structD)
    fmt.Println("结构体json编码:", string(structD))
    fmt.Println("结构体json解码:", _structD)

    dict,_ := json.Marshal(map[string]int{"id":1, "number":12312})
    var _dict map[string]int
    _ = json.Unmarshal([]byte(string(dict)), &_dict)
    fmt.Println("单一类型映射json编码:", string(dict))
    fmt.Println("单一类型映射json解码:", _dict)

    dict2,_ := json.Marshal(map[string]interface{}{"id":1,"title":"Hello World"})
    var _dict2 map[string]interface{}
    _ = json.Unmarshal([]byte(string(dict2)), &_dict2)
    fmt.Println("复杂类型映射json编码:", string(dict2))
    fmt.Println("复杂类型映射json解码:", _dict2)
}