编组json.RawMessage返回base64编码的字符串 [英] Marshalling json.RawMessage returns base64 encoded string
本文介绍了编组json.RawMessage返回base64编码的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我运行以下代码:
包主
导入(
encoding / json
fmt
)
func main(){
raw:= json.RawMessage(`{foo:bar}} `)
j,err:= json.Marshal(raw)
if err!= nil {
panic(err)
}
fmt.Println(string(j ))
}
Playground: http://play.golang.org/p/qbkEIZRTPQ
输出:
eyJmb28iOiJiYXIifQ ==
$ b 所需输出:
{为什么它base64编码我的 RawMessage
$ b $> / code>就好像它是普通的 [] byte
?
毕竟,RawMessage的实现MarshalJSON只是返回字节片段
// MarshalJSON返回* m作为JS ON编码m。
func(m * RawMessage)MarshalJSON()([] byte,error){
return * m,nil
}
解决方案
传递给 json.Marshal
必须是 json.RawMessage
才能正常工作的指针:
包(
encoding / json
fmt
)
:= json.RawMessage(`{foo:bar}`)
j,err:= json.Marshal(&raw)
if err!= nil {
panic err)
}
fmt.Println(string(j))
}
I run the following code:
package main
import (
"encoding/json"
"fmt"
)
func main() {
raw := json.RawMessage(`{"foo":"bar"}`)
j, err := json.Marshal(raw)
if err != nil {
panic(err)
}
fmt.Println(string(j))
}
Playground: http://play.golang.org/p/qbkEIZRTPQ
Output:
"eyJmb28iOiJiYXIifQ=="
Desired output:
{"foo":"bar"}
Why does it base64 encode my RawMessage
as if it was an ordinary []byte
?
After all, RawMessage's implementation of MarshalJSON is just returning the byte slice
// MarshalJSON returns *m as the JSON encoding of m.
func (m *RawMessage) MarshalJSON() ([]byte, error) {
return *m, nil
}
解决方案 Found the answer in a go-nuts thread
The value passed to json.Marshal
must be a pointer for json.RawMessage
to work properly:
package main
import (
"encoding/json"
"fmt"
)
func main() {
raw := json.RawMessage(`{"foo":"bar"}`)
j, err := json.Marshal(&raw)
if err != nil {
panic(err)
}
fmt.Println(string(j))
}
这篇关于编组json.RawMessage返回base64编码的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文