Golang解析json,结构体生成Json以及MD5加密

2022-01-13 11:06:56 浏览数 (1)

Golang实现MD5加密
代码语言:javascript复制
package main
  
import (
    "crypto/md5"
    "fmt"
)
  
func main() {
    data := []byte("crypted data")
    fmt.Printf("%x", md5.Sum(data))
}
Golang结构体生成Json
代码语言:javascript复制
package main
 
import (
    "encoding/json"
    "fmt"
)
 
//成员变量名首字母必须大写
type IT struct {
    Company  string
    Subjects []string
    IsOk     bool
    Price    float64
}
 
func main() {
    //定义一个结构体变量,同时初始化
    s := IT{"itcast", []string{"Go", "C  ", "Python", "Test"}, true, 666.666}
 
    //编码,根据内容生成json文本
    buf, err := json.Marshal(s)
    if err != nil {
        fmt.Println("err = ", err)
        return
    }
    fmt.Println("buf = ", string(buf))
}
Golang解析json
代码语言:javascript复制
package main
 
 
import (
    "fmt"
    "encoding/json"
)
 
func main() {
 
    b := []byte(`{"IP": "127.0.0.1", "name": "SKY"}`)
 
    m := make(map[string]string)
 
    err := json.Unmarshal(b, &m)
    if err != nil {
 
        fmt.Println("Umarshal failed:", err)
        return
    }
 
 
    fmt.Println("m:", m)
 
    for k,v :=range m {
        fmt.Println(k, ":", v)
    }
}

0 人点赞