Skip to content

JSON

JSON--序列化

  • 序列化 func Marshal(v interface{}) ([]byte, err)
    1. 结构体序列化
    2. Map序列化
  • tag(类似于注解,但是不对等)
  • 代码示例
    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Human struct {
        Name string
        Age  int
        From string
    }
    
    // Tag 形式
    // type Human struct {
    //  Name string `json:"n"`
    //  Age  int    `json:"a"`
    //  From string `json:"f"`
    // }
    /*
    MacintoshdeMacBook-Pro-139:json elasticnotes$ go run json.go
    struct序列化: {"n":"弹力笔记-struct","a":3,"f":"WEB"}
    map序列化: {"Age":3,"From":"WEB","Name":"弹力笔记-map"}
    */
    
    func SerializeStruct() {
        info := new(Human)
        info.Name = "弹力笔记-struct"
        info.Age = 3
        info.From = "WEB"
    
        // 序列化成 json字节数组
        data, err := json.Marshal(info)
        if err != nil {
            fmt.Println("Marshal err", err)
            return
        }
        fmt.Println("struct序列化:", string(data))
    }
    
    func SerializeMap() {
        info := make(map[string]interface{})
        info["Name"] = "弹力笔记-map"
        info["Age"] = 3
        info["From"] = "WEB"
    
        // 序列化成 json字节数组
        data, err := json.Marshal(info)
        if err != nil {
            fmt.Println("Marshal err:", err)
            return
        }
        fmt.Println("map序列化:", string(data))
    }
    
    func main() {
        SerializeStruct()
        SerializeMap()
    }
    
    
    // 输出
    MacintoshdeMacBook-Pro-139:json elasticnotes$ go run json.go 
    struct序列化 {"Name":"弹力笔记-struct","Age":3,"From":"WEB"}
    map序列化 {"Age":3,"From":"WEB","Name":"弹力笔记-map"}
    

JSON--反序列化

  • 反序列化 func Unmarshal(data []byte, v interface{}) error
  • 代码示例
    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Human struct {
        Name string
        Age  int
        From string
    }
    
    func DeSerializeStruct() {
        jsonString := `{"Name":"弹力笔记-struct","Age":3,"From":"WEB"}`
        info := new(Human)
        err := json.Unmarshal([]byte(jsonString), &info)
        if err != nil {
            fmt.Println("DeSerializeStruct Err:", err)
            return
        }
        fmt.Println("DeSerializeStruct:", info)
    
    }
    
    func DeSerializeMap() {
        jsonString := `{"Name":"弹力笔记-struct","Age":3,"From":"WEB"}`
        info := make(map[string]interface{})
        err := json.Unmarshal([]byte(jsonString), &info)
        if err != nil {
            fmt.Println("DeSerializeMap Err:", err)
            return
        }
        fmt.Println("DeSerializeMap:", info)
    }
    
    func main() {
        DeSerializeStruct()
        DeSerializeMap()
    }
    
    
    // 输出
    MacintoshdeMacBook-Pro-139:json v_yangyinglong$ go run json.go 
    DeSerializeStruct: &{弹力笔记-struct 3 WEB}
    DeSerializeMap: map[Age:3 From:WEB Name:弹力笔记-struct]