英文:
Embed struct but only have certain fields in json
问题
我有一个结构体,我想嵌入它,但只想对该结构体的某些字段进行JSON编码(并将它们转换为小写)。这可能吗?
package main
import (
"encoding/json"
"fmt"
"net/url"
)
type MyStruct struct {
Name string `json:"name"`
*url.URL
}
func main() {
m := &MyStruct{
"Bob",
&url.URL{
Scheme: "http",
},
}
j, err := json.Marshal(m)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(j)) // 希望输出 { "name": "Bob", "scheme": "http" }
}
以上是您要翻译的内容。
英文:
I have a struct that I want to embed but want to json encode only certain fields of that struct (and lowercase them). Is that possible?
https://play.golang.org/p/bEC4zlx2oC:
package main
import (
"encoding/json"
"fmt"
"net/url"
)
type MyStruct struct {
Name string `json:"name"`
*url.URL
}
func main() {
m := &MyStruct{
"Bob",
&url.URL{
Scheme: "http",
},
}
j, err := json.Marshal(m)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(j)) // want {"name":"Bob","scheme":"http"}
}
答案1
得分: 3
扩展我的评论并提供示例。
这是可行的,你需要实现Marshal接口。
例如:
func (u *MyStruct) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Name string `json:"name"`
Scheme string `json:"scheme"`
}{
Name: u.Name,
Scheme: u.Scheme,
})
}
Play链接:https://play.golang.org/p/LLchuOdYvf
输出:
{"name":"Bob","scheme":"http"}
英文:
Expanding my comment with example.
It is feasible, you have to implement Marshal interface.
For example:
func (u *MyStruct) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Name string `json:"name"`
Scheme string `json:"scheme"`
}{
Name: u.Name,
Scheme: u.Scheme,
})
}
Play Link: https://play.golang.org/p/LLchuOdYvf
Output:
{"name":"Bob","scheme":"http"}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论