涉及知识点
- struct和struct-tag
- 了解反射原理
- 了解reflection包
- 涉及函数方法 TypeOf、ValueOf、NumField、FieldByName、Field
实现思路
- 定义json对应的struct
- 给struct赋值
- 初始化变量 reflect.Type 、reflect.Value
- 使用函数 reflect.TypeOf reflect.ValueOf
- 循环组装json字符串
- 输出json字符串
代码实现
type goods struct {
ID int64 `json:"id"`
Title string `json:"title"`
}
func main() {
g := goods{ID: 1, Title:"IPhone 13 pro"}
var t reflect.Type
t = reflect.TypeOf(g)
var v reflect.Value
v = reflect.ValueOf(g)
json := "{"
for i := 0; i < t.NumField(); i++ {
json += "\"" + t.Field(i).Tag.Get("json") + "\":\"" + v.FieldName(t.Field(i).Name).String() + "\""
}
json += "}"
fmt.Println(json)
}
Was this article helpful to you?
Yes
No