简体   繁体   中英

Golang JSON RawMessage literal

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM