在运行时重写Golang JSON标记值
我在我的Web应用程序中使用“encoding/json”具有以下结构 讲座和Cos本身都是复杂的结构,我不想包含在序列化的json中,我通过设置json来表示:“-” 这很好用 我想在运行时按需重写该行为,在不编写自己的序列化代码的情况下如何做到这一点 编辑:我自己的解决方案:在运行时重写Golang JSON标记值,json,go,Json,Go,我在我的Web应用程序中使用“encoding/json”具有以下结构 讲座和Cos本身都是复杂的结构,我不想包含在序列化的json中,我通过设置json来表示:“-” 这很好用 我想在运行时按需重写该行为,在不编写自己的序列化代码的情况下如何做到这一点 编辑:我自己的解决方案: func (r *CourseAssignment) Expand(depth int) CourseAssignment { if depth <= 0 { return *r
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"`
}
func(r*courseasignment)Expand(depth int)courseasignment{
如果深度您可以使用StructTag
从reflect
包中读取/获取结构标记值:
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"))
}
没有方法更改标准库中的结构标记字段
但是,也有一些开源库可以做到这一点,比如。我在类似情况下所做的是将这些字段设置为省略empty
,然后在序列化之前清空它们,如果我不希望它们包含在JSON中:
type CourseAssignment struct {
Semester int `json:"semester" xml:"semester"`
Lecture *Lecture `json:"lecture,omitempty" xml:"-"`
Cos *Cos `json:"cos,omitempty" xml:"-"`
Links map[string][]Link `json:"links,omitempty" xml:"links,omitempty"`
}
// Want to serialize without including Lecture/Cos:
aCourseAssignment.Lecture = nil
aCourseAssignment.Cos = nil
thing,err := json.Marshal(aCourseAssignment)
谢谢你的提示,我最后做了类似的事情:当我们想要避免结果中包含字段名时,这是没有用的。@Pinkpather你怎么看?如果字段为空,省略empty
的要点是字段被省略。你应该试着将核心模型嵌套在另一个包装器模型中,如本博文:inste中所述这个黑客的广告
type CourseAssignment struct {
Semester int `json:"semester" xml:"semester"`
Lecture *Lecture `json:"lecture,omitempty" xml:"-"`
Cos *Cos `json:"cos,omitempty" xml:"-"`
Links map[string][]Link `json:"links,omitempty" xml:"links,omitempty"`
}
// Want to serialize without including Lecture/Cos:
aCourseAssignment.Lecture = nil
aCourseAssignment.Cos = nil
thing,err := json.Marshal(aCourseAssignment)