Golang JSON的序列化和反序列化

Golang大约 2452 字

序列化

json.Marshal

结构体

Golang设定结构体字段小写为不可导出,无法序列化不可导出字段。大写字段导出后JSON字符串也将大写,故使用struct tag添加标注json自定义JSON字段名。

type Result struct {
    Code int         `json:"code"`
    Msg  string      `json:"msg"`
    Data interface{} `json:"data"`
}

func main() {
    result := &Result{0, "请求成功", "this is data"}
    resultStr, _ := json.Marshal(result)
    // {"code":0,"msg":"请求成功","data":"this is data"}
    fmt.Printf("Result JSON format: %s\n", resultStr)
}

map

func main() {
    m := make(map[string]interface{})
    m["id"] = 1
    m["price"] = 10.24
    m["vip"] = true
    m["create_ts"] = "2020-10-28"
    m["remark"] = nil
    mapStr, _ := json.Marshal(m)
    // {"create_ts":"2020-10-28","id":1,"price":10.24,"remark":null,"vip":true}
    fmt.Printf("Map JSON format: %s\n", mapStr)
}

反序列化

json.Unmarshal

结构体

type Address struct {
    Type    string
    City    string
    Country string
}

func main() {
    addressJsonStr := `{"Type":"CN","City":"Shanghai","Country":"China"}`
    var address Address
    err = json.Unmarshal([]byte(addressJsonStr), &address)
    if err != nil {
        log.Println(err)
    }
    // {CN Shanghai China}
    fmt.Println(address)
}

map

func main() {
    addressJsonStr := `{"Type":"CN","City":"Shanghai","Country":"China"}`
    m2 := make(map[string]interface{})
    err = json.Unmarshal([]byte(addressJsonStr), &m2)
    // map[City:Shanghai Country:China Type:CN]
    fmt.Println(m2)
}

json.NewDecoder

json.NewDecoder接收一个io.Reader参数,对于大批量的JSON字符串,它分批加载处理,故比json.Unmarshal性能更佳。

func main() {
    const jsonStream = `
    [
        {"Name": "Ed", "Text": "Knock knock."},
        {"Name": "Sam", "Text": "Who's there?"},
        {"Name": "Ed", "Text": "Go fmt."},
        {"Name": "Sam", "Text": "Go fmt who?"},
        {"Name": "Ed", "Text": "Go fmt yourself!"}
    ]
`
    var i []map[string]interface{}

    decoder := json.NewDecoder(strings.NewReader(jsonStream))
    err = decoder.Decode(&i)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(i)
}

HTTP服务的POST请求中,可以用来直接反序列化前端传上来的JSON字符串。

type User struct {
    Name string
    Age int
}

// json.NewDecoder(r.Body)
func HandleUse(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    var u User
    if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
        w.WriteHeader(http.StatusBadRequest)
        return
    }
    w.WriteHeader(http.StatusOK)
    _, _ = fmt.Fprintf(w, "姓名:%s,年龄:%d", u.Name, u.Age)
}
阅读 48 · 发布于 2020-11-02

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批