一、使用内置工具
import ( "encoding/json" "fmt" "testing" ) //使用FeildTag标识对应的json type BasicInfo struct { Name string `json:"name"` Age int `json:"age"` } type JobInfo struct { Skills []string `json:"skills"'` } type Employee struct { BasicInfo BasicInfo `json:"base_info"` JobInfo JobInfo `json:"job_info"` } var jsonStr = `{ "base_info": { "age": 30, "name": "Mike" }, "job_info": { "skills": [ "Java", "Go", "C" ] } } ` func TestEmbeddedJson(t *testing.T) { e := new(Employee) //josn 字符串到对象 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) } }
=== RUN TestEmbeddedJson {{Mike 30} {[Java Go C]}} {"base_info":{"name":"Mike","age":30},"job_info":{"skills":["Java","Go","C"]}} --- PASS: TestEmbeddedJson (0.00s) PASS
二、使用第三方工具
#安装 go get -u github.com/mailru/easyjson/... #参考资料 https://github.com/mailru/easyjson
使用easyjson生成JSON处理代码
easyjson -all ./json_data.go
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"` }
import ( "encoding/json" "fmt" "testing" ) var jsonStr = `{ "basic_info":{ "name":"Mike", "age":30 }, "job_info":{ "skills":["Java","Go","C"] } } ` func TestEasyJson(t *testing.T) { e := Employee{} e.UnmarshalJSON([]byte(jsonStr)) fmt.Println(e) if v, err := e.MarshalJSON(); err != nil { t.Error(err) } else { fmt.Println(string(v)) } }
=== RUN TestEasyJson {{Mike 30} {[Java Go C]}} {"basic_info":{"name":"Mike","age":30},"job_info":{"skills":["Java","Go","C"]}} --- PASS: TestEasyJson (0.00s) PASS