英文:
How to remove duplicate json information on struct
问题
我有以下可以工作的代码:
type Q struct {
Links struct {
Self struct {
Href string `json:"href"`
} `json:"self"`
} `json:"_links"`
CreatedAt time.Time `json:"created_at"`
ID uuid.UUID `json:"id"`
Name string `json:"name"`
UpdatedAt time.Time `json:"updated_at"`
}
expected, _ := json.Marshal(Q{
Links: struct {
Self struct {
Href string `json:"href"`
} `json:"self"`
}{
Self: struct {
Href string `json:"href"`
}{
Href: url,
},
},
ID: id,
Name: name,
CreatedAt: now,
UpdatedAt: now,
})
然而,我发现json
字段的重复很糟糕,有可能从expected
中删除它吗?如果我删除它会返回错误。
英文:
I have the following code that works
type Q struct {
Links struct {
Self struct {
Href string `json:"href"`
} `json:"self"`
} `json:"_links"`
CreatedAt time.Time `json:"created_at"`
ID uuid.UUID `json:"id"`
Name string `json:"name"`
UpdatedAt time.Time `json:"updated_at"`
}
expected, _ := json.Marshal(Q{Links: struct {
Self struct {
Href string `json:"href"`
} `json:"self"`
}{
Self: struct {
Href string `json:"href"`
}{
Href: url,
},
},
ID: id,
Name: name,
CreatedAt: now,
UpdatedAt: now,
})
However, I find bad the repeteation of json
fields, it is possible to remove it from expected
? If I remove it returns an error
答案1
得分: 3
声明每个结构体为命名类型将避免重复编写整个结构体类型:
type Q struct {
Links Links `json:"_links"`
CreatedAt time.Time `json:"created_at"`
ID string `json:"id"`
Name string `json:"name"`
UpdatedAt time.Time `json:"updated_at"`
}
type Links struct {
Self Self `json:"self"`
}
type Self struct {
Href string `json:"href"`
}
func main() {
expected, _ := json.Marshal(
Q{Links: Links{
Self: Self{
Href: "testurl",
},
},
ID: "testid",
Name: "testname",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
})
fmt.Println(string(expected))
}
英文:
Declaring each struct as a named type will avoid having to rewrite the whole struct type repeatedly:
type Q struct {
Links Links `json:"_links"`
CreatedAt time.Time `json:"created_at"`
ID string `json:"id"`
Name string `json:"name"`
UpdatedAt time.Time `json:"updated_at"`
}
type Links struct {
Self Self `json:"self"`
}
type Self struct {
Href string `json:"href"`
}
func main() {
expected, _ := json.Marshal(
Q{Links: Links{
Self: Self{
Href: "testurl",
},
},
ID: "testid",
Name: "testname",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
})
fmt.Println(string(expected))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论