首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >json.Marshal对Encoder.Encode

json.Marshal对Encoder.Encode
EN

Stack Overflow用户
提问于 2020-06-14 23:22:45
回答 2查看 2.3K关注 0票数 0

在以下代码中:

代码语言:javascript
复制
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

在以下代码中:

代码语言:javascript
复制
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()?因为bufjohnJSON都是[]byte类型

代码语言:javascript
复制
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.
}
EN

回答 2

Stack Overflow用户

发布于 2020-06-14 23:31:31

有三个不同之处。

如果Marshal函数和Encoder类型之间的特性差异不能在它们之间指定选择,那么使用最方便的方法。Marshal函数和编码器类型共享了它们的大部分实现,并具有相似的性能。Marshal函数并不像在另一个答案中所声称的那样是围绕编码器的包装器。

票数 4
EN

Stack Overflow用户

发布于 2020-06-14 23:33:03

Marshal (Unmarshal)是围绕Encoder (Decoder)的包装器。它们主要是方便功能,为底层编解码实现提供了方便的接口。

如果需要处理包含多个JSON文档的JSON流,或者需要处理JSON流而不将整个文档解封为内存中的结构,则使用解码器。如果您有一个Reader,您可以使用Decoder而不是Unmarshal

类似地,如果您正在生成没有内存结构的JSON流,或者正在将多个JSON文档写入流中,请使用Encoder。如果您有一个Writer,您可以使用一个编码器,而无需首先将其解组到一个字节数组中,然后编写它。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62379309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档