go 内置反射解析json 个人感觉有数据验证的作用
2022年1月19日数据结构文件 struct_def.go
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package jsontest 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"` } |
解析数据 embedded_json_test.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package jsontest import ( "encoding/json" "fmt" "testing" ) var jsonStr = `{ "basic_info":{ "name":"Mike", "age":30 }, "job_info":{ "skills":["Java","Go","C"] } } ` func TestEmbeddedJson(t *testing.T) { e := new(Employee) //获取里面的值 if err := json.Unmarshal([]byte(jsonStr), e); err != nil { t.Error(err) } t.Log(*e) if v, err := json.Marshal(e); err != nil { t.Error(err) } else { fmt.Println(string(v)) t.Log(string(v)) } } |