英文:
Golang JSON RawMessage literal
问题
在Golang中创建json.RawMessage字面量是可能的。
你可以像这样做:
type ErrorMessage struct {
Timestamp string
Message json.RawMessage
}
func getTestData() ErrorMessage {
return ErrorMessage{
Timestamp: "test-time",
Message: []byte("{}"),
}
}
或者类似这样。这个链接是我见过的最简洁的例子。我没有找到一个用于创建原始JSON消息的“struct”字面量的示例。
英文:
Is it possible to create a json.RawMessage literal in Golang?
I want to be able to do something like this:
type ErrorMessage struct {
Timestamp string
Message json.RawMessage
}
func getTestData() ErrorMessage {
return ErrorMessage{
Timestamp: "test-time",
Message: "{}"
}
}
Or something like that. This is the most succinct I've seen. I have not been able to find an example of a "struct" literal for creating raw json messages.
答案1
得分: 13
json.RawMessage 的底层数据类型是 []byte
。
你可以将字符串转换为字节切片,或直接在字面量中使用字节切片。
msg := ErrorMessage{
Timestamp: "test-time",
Message: []byte("{}"),
}
请注意,为了按预期进行编组,你需要使用 *json.RawMessage
,但在字面量上下文中无法取地址。
英文:
The underlying data type for json.RawMessage is a []byte
You can convert your string, or use a byte slice directly in the literal
msg := ErrorMessage{
Timestamp: "test-time",
Message: []byte("{}"),
}
Note that to actually marshal that as expected, you need to use *json.RawMessage
, which you can't take the address of in a literal context.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论