英文:
Append string to member when encoding a type to JSON
问题
我有一个类型,其中有一个名为"Url"的值成员。当将该类型编码为JSON时,我想在Url前面添加HOST值。实现这一目标的最佳方法是什么?
在这个例子中,Println
语句打印出{"url":"/thisurl"}
,我希望它打印出{"url":"http://myhost.com/thisurl"}
。
package main
import "fmt"
import "encoding/json"
type Post struct {
Url string `json:"url"`
}
const (
HOST = "http://myhost.com"
)
func main() {
post := Post{"/thisurl"}
marshaled, _ := json.Marshal(post)
fmt.Println(string(marshaled))
//{"url":"/thisurl"}
}
更新
我可以在json.Marshal
行之前重新分配post.Url
post.Url = fmt.Sprintf("%s%s", HOST, post.Url)
但这感觉有点凌乱,如果我每次想要编码为JSON时都要记得重新分配。
我不想改变post.Url
的值,我只想改变它在JSON中的表示方式。
英文:
I have this type with a value member called "Url". When encoding this type to json, I want to prepend the HOST value in front of the Url. What is the best way to achieve that?
In this example, the Println
statement prints {"url":"/thisurl"}
, I want it to print {"url":"http://myhost.com/thisurl"}
package main
import "fmt"
import "encoding/json"
type Post struct {
Url string `json:"url"`
}
const (
HOST = "http://myhost.com"
)
func main() {
post := Post{"/thisurl"}
marshaled, _ := json.Marshal(post)
fmt.Println(string(marshaled))
//{"url":"/thisurl"}
}
Update
I could re-assign post.Url right before the json.Marshal
line
post.Url = fmt.Sprintf("%s%s", HOST, post.Url)
But that feels a little messy, if I have to remember to do a reassignment every time I want to encode to json.
I don't want to change the value of post.Url
, I simply want to change how it is represented as json.
答案1
得分: 3
如果您想更改(非)编组行为,请使用实现了json.Marshaler
(可能还有json.Unmarshaler
)的自定义类型。
package main
import (
"encoding/json"
"fmt"
)
type Post struct {
URL URLString `json:"url"`
}
const (
Host = "http://myhost.com"
)
type URLString string
func (u URLString) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s%s"`, Host, u)), nil
}
func main() {
post := Post{"/thisurl"}
marshaled, _ := json.Marshal(post)
fmt.Println(string(marshaled))
//{"url":"http://myhost.com/thisurl"}
}
(还要注意,使用全大写字母表示常量不符合惯例,golint
建议使用URL
、MyURL
、HTTP
、ID
而不是Url
、MyUrl
或Id
)。
英文:
If you want to change the (un)marshalling behaviour then use a custom type that implements json.Marshaler
(and possibly json.Unmarshaler
).
package main
import (
"encoding/json"
"fmt"
)
type Post struct {
URL URLString `json:"url"`
}
const (
Host = "http://myhost.com"
)
type URLString string
func (u URLString) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s%s"`, Host, u)), nil
}
func main() {
post := Post{"/thisurl"}
marshaled, _ := json.Marshal(post)
fmt.Println(string(marshaled))
//{"url":"http://myhost.com/thisurl"}
}
(also note, using all caps for constants is not idiomatic, and golint
recommends URL
, MyURL
, HTTP
, ID
vs Url
, MyUrl
, or Id
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论