我正在制作一个 Go 服务,该服务从不同来源收集 JSON 对象并将它们聚合到一个 JSON 对象中。
我想知道是否有任何方法可以聚合子对象而无需再次解码和重新编码它们或手动构建 JSON 字符串。
我正在考虑使用包含已经编码的部分的 struct
,例如:
type Event struct {
Place string `json:"place"`
Attendees string `json:"attendees"`
}
其中 Place
和 Attendees
本身是 JSON 字符串。我想以某种方式将它们标记为“已编码”,这样它们就不会以转义的 JSON 字符串结束,而是按原样使用。
有什么办法可以实现吗?
最佳答案
您可以使用 json.RawMessage
RawMessage is a raw encoded JSON object. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding.
此外,json.RawMessage
是 []byte
的别名,因此您可以通过这种方式为其赋值:
v := json.RawMessage(`{"foo":"bar"}`)
例子:
package main
import (
"encoding/json"
"fmt"
)
type Event struct {
Place json.RawMessage `json:"place"`
Attendees json.RawMessage `json:"attendees"`
}
func main() {
e := Event{
Place: json.RawMessage(`{"address":"somewhere"}`),
Attendees: json.RawMessage(`{"key":"value"}`),
}
c, err := json.Marshal(&e)
if err != nil {
panic(err)
}
fmt.Println(string(c))
// {"place":{"address":"somewhere"},"attendees":{"key":"value"}}
}
关于json - 在 Go 中聚合 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37573395/