使用Go语言对Json对象进行编码解码

本文转自https://freeaihub.com/article/decode-and-encode-json-in-go.html,该页可在线进行实验。

将演示如何使用Go语言中encoding/json package,结合建立一台http-server响应对JSON数据对象进行编码与解码的操作。
JSON简介

因为XML整合到HTML中各个浏览器实现的细节不尽相同,Douglas Crockford和 Chip Morningstar一起从JS的数据类型中提取了一个子集,作为新的数据交换格式,因为主流的浏览器使用了通用的JavaScript引擎组件,所以在解析这种新数据格式时就不存在兼容性问题,于是他们将这种数据格式命名为 “JavaScript Object Notation”,缩写为 JSON。

配置Go语言运行环境

cp /share/tar/go1.12.9.linux-amd64.tar.gz .
 
tar -C /usr/local -xzvf go1.12.9.linux-amd64.tar.gz
 
echo export PATH=$PATH:/usr/local/go/bin >> /etc/profile
 
source /etc/profile

go version

编写Go语言http server程序

cat >> json.go << EOF
// json.go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

type User struct {
    Firstname string `json:"firstname"`
    Lastname  string `json:"lastname"`
    Age       int    `json:"age"`
}

func main() {
    http.HandleFunc("/decode", func(w http.ResponseWriter, r *http.Request) {
        var user User
        json.NewDecoder(r.Body).Decode(&user)

        fmt.Fprintf(w, "%s %s is %d years old!", user.Firstname, user.Lastname, user.Age)
    })

    http.HandleFunc("/encode", func(w http.ResponseWriter, r *http.Request) {
        peter := User{
            Firstname: "John",
            Lastname:  "Doe",
            Age:       25,
        }

        json.NewEncoder(w).Encode(peter)
    })

    http.ListenAndServe(":80", nil)
}
EOF

运行程序及开启服务器进行验证

go run json.go &

curl -s -XPOST -d '{"firstname":"Elon","lastname":"Mars","age":48}' 
curl -s http://localhost/encode

总结

以上代码及案例实操演示了如何使用Go语言中encoding/json package使用

猜你喜欢

转载自www.cnblogs.com/freeaihub/p/13167439.html