编组json.RawMessage会返回Base64编码的字符串。

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

Marshalling json.RawMessage returns base64 encoded string

问题

我运行了以下代码:

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

输出:

"eyJmb28iOiJiYXIifQ=="

期望的输出:

{"foo":"bar"}

为什么它将我的RawMessage编码为Base64,就像它是普通的[]byte一样?

毕竟,RawMessageMarshalJSON实现只是返回字节切片:

// MarshalJSON returns *m as the JSON encoding of m.
func (m *RawMessage) MarshalJSON() ([]byte, error) {
	return *m, nil
}
英文:

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 
}

答案1

得分: 72

在一个go-nuts的讨论帖子中找到了答案。

传递给json.Marshal的值必须是一个指针,以使json.RawMessage正常工作:

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))
}
英文:

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))  
}

huangapple
  • 本文由 发表于 2014年6月15日 19:37:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/24229205.html
匿名

发表评论

匿名网友

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

确定