在以下代码中:
package main
import (
"bytes"
"encoding/json"
"fmt"
)
type Student struct {
Firstname, lastname string
Email string
Age int
HeightInMeters float64
IsMale bool
}
func main() {
john := Student{
Firstname: "John",
lastname: "Doe",
Age: 21,
HeightInMeters: 1.75,
IsMale: true,
}
johnJSON, _ := json.Marshal(john) // johnJSON is of type []byte
fmt.Println(string(johnJSON)) // print it in characters
}johnJSON, _ := json.Marshal(john)正在将结构类型(john)编码为[]byte。
在以下代码中:
package main
import (
"bytes"
"encoding/json"
"fmt"
)
type Student struct {
Firstname, lastname string
Email string
Age int
HeightInMeters float64
IsMale bool
}
func main() {
john := Student{
Firstname: "John",
lastname: "Doe",
Age: 21,
HeightInMeters: 1.75,
IsMale: true,
}
// johnJSON, _ := json.Marshal(john) // johnJSON is of type []byte
// fmt.Println(string(johnJSON)) // print it in characters
// create a buffer to hold JSON data
buf := new(bytes.Buffer)
// create JSON encoder for `buf`
bufEncoder := json.NewEncoder(buf)
bufEncoder.Encode(john)
// print contents of the `buf`
fmt.Println(buf) // calls `buf.String()` method
}bufEncoder.Encode(john)正在将结构类型(john)封送到io.Writer类型(buf)。
什么时候使用json.Marshal()和Encoder.Encode()?因为buf和johnJSON都是[]byte类型
type Buffer struct {
buf []byte // contents are the bytes buf[off : len(buf)]
off int // read at &buf[off], write at &buf[len(buf)]
lastRead readOp // last read operation, so that Unread* can work correctly.
}发布于 2020-06-14 23:31:31
有三个不同之处。
[]byte。编码器将数据写入底层io.Writer,从而避免了将整个编码文档存储在内存中的需要。如果Marshal函数和Encoder类型之间的特性差异不能在它们之间指定选择,那么使用最方便的方法。Marshal函数和编码器类型共享了它们的大部分实现,并具有相似的性能。Marshal函数并不像在另一个答案中所声称的那样是围绕编码器的包装器。
发布于 2020-06-14 23:33:03
Marshal (Unmarshal)是围绕Encoder (Decoder)的包装器。它们主要是方便功能,为底层编解码实现提供了方便的接口。
如果需要处理包含多个JSON文档的JSON流,或者需要处理JSON流而不将整个文档解封为内存中的结构,则使用解码器。如果您有一个Reader,您可以使用Decoder而不是Unmarshal。
类似地,如果您正在生成没有内存结构的JSON流,或者正在将多个JSON文档写入流中,请使用Encoder。如果您有一个Writer,您可以使用一个编码器,而无需首先将其解组到一个字节数组中,然后编写它。
https://stackoverflow.com/questions/62379309
复制相似问题