dscc90150010 2018-08-25 19:21
浏览 37

在解组字段的JSON内容时打印结构字段标签?

In Go, Is it possible to get the tags from a struct field while I'm unmarshaling JSON content to it? Here's my failed attempt at doing so:

package main
import (
  "log"
  "encoding/json"
)
type Person struct {
  ProfileName AltField `json:"profile_name"`
}

type AltField struct {
  Val string
}

func (af *AltField) UnmarshalJSON(b []byte) error {
  log.Println("Show tags")
  //log.Println(af.Tag) // I want to see `json:"profile_name"`
  if e := json.Unmarshal(b,&af.Val); e != nil {
    return e
  }
  return nil
}
func main() {
  p := Person{}
  _ = json.Unmarshal([]byte(`{"profile_name":"Af"}`),&p)

}

I commented out the line log.Println(af.Tag) because it causes compilation errors. If I can get a handle on the tags from the Person struct, that will allow me to develop some other conditional logic.

Is this possible?

  • 写回答

1条回答 默认 最新

  • dongshai1944 2018-08-25 19:31
    关注

    Use reflection to get the value of struct field tag. The reflect package provides functions to work with tags including to get the value of tag

    package main
    
    import (
      "log"
      "encoding/json"
      "reflect"
    )
    type Person struct {
      ProfileName AltField `json:"profile_name"`
    }
    
    type AltField struct {
      Val string `json:"val"`
    }
    
    func (af *AltField) UnmarshalJSON(b []byte) error {
      field, ok := reflect.TypeOf(*af).FieldByName("Val")
      if !ok {
        panic("Field not found")
      }
      log.Println(string(field.Tag))
    
      if e := json.Unmarshal(b,&af.Val); e != nil {
        return e
      }
      return nil
    }
    
    func main() {
      p := Person{}
      _ = json.Unmarshal([]byte(`{"profile_name":"Af"}`),&p)
    
    }
    

    You can only get the value of those field tags which has them. The struct field reflect object should be created for fetching the tags of its fields.

    Working Code on Playground

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题