dongwei3120 2018-09-07 18:30
浏览 10

在自定义UnmarshallJson函数中使用对时间字段的反射

I am trying to use reflection to take the time fields from a struct and through a custom UnmarshallJSON func, see which ones come across as the time.IsZero value and which ones dont. They are coming across as *time.Time and I dont want to use omitempty (as I cant, and need the field to be cleared and persisted as such). Right now I am checking each field individually, but I was wondering if there was a way to do it through reflection to make it more robust, if another time field was added, I didnt need to add the corresponding check for it.

Right now this is how im doing it:

type A struct {
    X *time.Time `json:"x"`
    Y *time.Time `json:"y"`

}

func (a *A) UnmarshalJSON(b []byte) (err error) {
    type Alias A
    s := &struct {
      X time.Time `json:"x"`
      Y time.Time `json:"y"`
}{
        Alias: (*Alias)(a),
    }
    if err := json.Unmarshal(b, &s); err != nil {
        return err
    }

if s.X.IsZero() {
        a.X = nil
    } else {
        a.X = &s.X
    }

if s.Y.IsZero() {
        a.Y = nil
    } else {
        a.Y = &s.Y
    }

I would rather not have to check each time field and instead do something like this

values := reflect.ValueOf(&s).Elem()

for i := 0; i < values.NumField(); i++ {
    fieldName := values.Type().Field(i).Name
    fieldValue := values.Field(i).Interface()
    if fieldValue == nil {
        a.fieldName = nil
    } else {
      a.fieldName = &s.fieldName
    }

The problem comes when I try to do a.fieldName or s.fieldName, am I missing something? has anyone ran into this or (hopefully) solved this problem?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 多址通信方式的抗噪声性能和系统容量对比
    • ¥15 winform的chart曲线生成时有凸起
    • ¥15 msix packaging tool打包问题
    • ¥15 finalshell节点的搭建代码和那个端口代码教程
    • ¥15 Centos / PETSc / PETGEM
    • ¥15 centos7.9 IPv6端口telnet和端口监控问题
    • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
    • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
    • ¥20 海浪数据 南海地区海况数据,波浪数据
    • ¥20 软件测试决策法疑问求解答