Golang JSON RawMessage 字面量

huangapple go评论90阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年5月30日 02:53:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/30537035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定