Go内置json解析 配置文件解析
package json
import (
"encoding/json"
"fmt"
"testing"
)
type BasicInfo struct {
Name string `json:"name"`
Age int `json:"age"`
}
type JobInfo struct {
Skills []string `json:"skills"`
}
type Employee struct {
BasicInfo BasicInfo `json:"basic_info"`
JobInfo JobInfo `json:"job_info"`
}
var jsonStr = `{
"basic_info":{
"name":"Mike",
"age":30
},
"job_info":{
"skills":["Java","Go","C"]
}
}`
func TestEmbeddedJson(t *testing.T) {
e := new(Employee)
err := json.Unmarshal([]byte(jsonStr), e)
if err != nil {
t.Error(err)
}
fmt.Println(*e)
if v,err := json.Marshal(e);err == nil{
fmt.Println(string(v))
} else {
t.Error(err)
}
}
不用反射的Json解析 Easy解析 网络
//安装 go get-u github.com/mailru/easyjson/...
//使用easyjson -all <结构定义>.go
//采用了代码生成而非反射
//使用UnmarshalJSON MarshalJSON 调用了
//使用benchmark 比较性能 go test -bench=.