打赏

golang easyjson使用

golang easyjson使用

1.先安装easyjson

go get -u github.com/mailru/easyjson/

2.在结构体上加//easyjson:json的注解

//easyjson:json
type School struct {
	Name string		`json:"name"`
	Addr string		`json:"addr"`
}

//easyjson:json
type Student struct {
	Id       int       `json:"id"`
	Name     string    `json:"s_name"`
	School   School    `json:"s_chool"`
	Birthday time.Time `json:"birthday"`
}

3.执行命令生成easyjson文件

easyjson  -all student.go  // 生成easyjson_student.go,为结构体增加了MarshalJSON、UnmarshalJSON方法

4.使用示例

package main

import (
    "studygo/easyjson"
    "time"
    "fmt"
)

func main(){
    s:=easyjson.Student{
        Id: 11,
        Name:"qq",
        School:easyjson.School{
            Name:"CUMT",
            Addr:"xz",
        },
        Birthday:time.Now(),
    }
    bt,err:=s.MarshalJSON()  // MarshalJSON
    fmt.Println(string(bt),err)
    
    json:=`{"id":11,"s_name":"qq","s_chool":{"name":"CUMT","addr":"xz"},"birthday":"2017-08-04T20:58:07.9894603+08:00"}`
    ss:=easyjson.Student{}
    ss.UnmarshalJSON([]byte(json))  // UnmarshalJSON
    fmt.Println(ss)
}

说明:常见的json库:ffjson、json-iterator/go、go-simplejson, gabs, jason,jsonparser

相关链接

https://www.cnblogs.com/52fhy/p/11830755.html

posted @ 2021-04-17 23:12  苍山落暮  阅读(1648)  评论(0编辑  收藏  举报