1. Home
  2. Docs
  3. golang
  4. 代码练习
  5. 如何利用golang反射将struct转成json字符串?

如何利用golang反射将struct转成json字符串?

涉及知识点

  • struct和struct-tag
  • 了解反射原理
  • 了解reflection包
  • 涉及函数方法 TypeOf、ValueOf、NumField、FieldByName、Field

实现思路

  1. 定义json对应的struct
  2. 给struct赋值
  3. 初始化变量 reflect.Type 、reflect.Value
  4. 使用函数 reflect.TypeOf reflect.ValueOf
  5. 循环组装json字符串
  6. 输出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

How can we help?