dongxie1907 2017-07-11 10:53
浏览 73

在运行时覆盖Golang JSON标签值

I have the following struct in in my Web Application using "encoding/json"

type CourseAssignment struct {
    Semester int `json:"semester"  xml:"semester"`
    Lecture Lecture `json:"-"  xml:"-"`
    Cos Cos `json:"-"  xml:"-"`
    Links map[string][]Link `json:"links,omitempty" xml:"links,omitempty"`
}

Lecture and Cos are complex structs themselves that i dont want to be included in my serialized json which i indicate by setting json:"-"

This works perfectly.

I want to override that behavior on demand during runtime, how do i do that without writing my own Serialization code ?

Edit: My Own Solution:

func (r *CourseAssignment) Expand(depth int) CourseAssignment {

    if depth <= 0 {
        return *r
    }

    tmp := *r
    tmp.LectureEx = tmp.Lecture
    tmp.CosEx = tmp.Cos
    tmp.Links = nil 
    return tmp
}

type CourseAssignment struct {
    Semester int `json:"semester"  xml:"semester"`
    Lecture *Lecture `json:"-"  xml:"-"`
    Cos *Cos `json:"-"  xml:"-"`
    Links map[string][]Link `json:"links,omitempty" xml:"links,omitempty"`
    LectureEx  *Lecture   `json:"lecture,omitempty"  xml:"lecture,omitempty"`
    CosEx *Cos `json:"course_of_study,omitempty" xml:"course_of_study,omitempty"`   
}

When i want to include the fields i create a Copy of the Object using expand that fills fields that contain the same references but show up in the serialization.

  • 写回答

2条回答 默认 最新

  • douxi7219 2017-07-11 11:03
    关注

    You can read/get struct tag values using StructTag from reflect package:

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type CourseAssignment struct {
        Semester int `json:"semester"  xml:"semester"`
    }
    
    func main() {
        ca := CourseAssignment{}
        st := reflect.TypeOf(ca)
        field := st.Field(0)
        fmt.Println(field.Tag.Get("json"))
    }
    

    There is no method to change a struct tag field in the standard library.

    However, there are open-source libraries that do exactly that, like Retag.

    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图