gpt4 book ai didi

json.Marshal 与 Encoder.Encode

转载 作者:行者123 更新时间:2023-12-01 22:38:08 29 4
gpt4 key购买 nike

在下面的代码中:

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() ?因为两者 bufjohnJSON[]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.
}

最佳答案

Marshal ( Unmarshal ) 是 Encoder 的包装。 (Decoder)。它们主要是便利功能,为较低级别的编码器/解码器实现提供方便的接口(interface)。

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

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

关于json.Marshal 与 Encoder.Encode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62379309/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com