在Golang中,JSON编码和编组之间有什么区别?

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

in Golang, what is the difference between json encoding and marshalling

问题

JSON的“编码/解码”和“序列化/反序列化”之间有什么区别?

我正在尝试学习如何在Go语言中编写一个RESTful API,但不确定JSON的“编码”和“序列化”之间的区别,或者它们是否相同?

英文:

What is the difference between JSON 'encoding/decoding' and JSON 'marshalling/unmarshalling'?

Trying to learn how to write a RESTFUL api in golang and not sure what the difference between JSON 'encoding' and 'marshalling' is or if they are the same?

答案1

得分: 75

  • Marshal => String
  • Encode => Stream

Marshal和Unmarshal将字符串转换为JSON,反之亦然。
编码和解码将流转换为JSON,反之亦然。

下面的代码展示了marshal和unmarshal的工作原理:

type Person struct {
    First string
    Last  string
}

func main() {
    /* 这将把JSON编组为[]bytes */

    p1 := Person{"alice", "bob"}
    bs, _ := json.Marshal(p1)
    fmt.Println(string(bs))

    /* 这将从[]bytes解组JSON */

    var p2 Person
    bs = []byte(`{"First":"alice","Last":"bob"}`)
    json.Unmarshal(bs, &p2)
    fmt.Println(p2)
}

编码器和解码器将结构体写入流的切片,或者从流的切片中读取数据并将其转换为结构体。在内部,它还实现了marshal方法。唯一的区别是,如果你想处理字符串或字节,请使用marshal;如果你想读取或写入某个writer接口的任何数据,请使用encode和decode。

英文:
  • Marshal => String
  • Encode => Stream

Marshal and Unmarshal convert a string into JSON and vice versa.
Encoding and decoding convert a stream into JSON and vice versa.

The below code show working of marshal and unmarshal

type Person struct {
First string
Last string
}
func main() {
    /* This will marshal the JSON into []bytes */

	p1 := Person{"alice", "bob"}
	bs, _ := json.Marshal(p1)
	fmt.Println(string(bs))

    /* This will unmarshal the JSON from []bytes */

    var p2 Person
    bs = []byte(`{"First":"alice","Last":"bob"}`)
    json.Unmarshal(bs, &p2)
    fmt.Println(p2)

}

Encoder and decoder write struct to slice of a stream or read data from a slice of a stream and convert it into a struct. Internally, it also implements the marshal method. The only difference is if you want to play with string or bytes use marshal, and if any data you want to read or write to some writer interface, use encodes and decode.

答案2

得分: 18

通常,编码/解码JSON是指将字符数据实际读取/写入字符串或二进制形式的过程。编组/解组是指将JSON类型与Go数据类型和基本类型进行映射的过程。

实际的编码可以包括将Unicode字符序列化为字符串的操作。我认为在文档中它们有时可以互换使用,因为它们通常在同一步骤中发生。例如,Marshal函数将确定要将某个内容编组为哪种JSON类型,然后将其以字符串形式进行编码(如果是文本数据,则可能包括其他细节,如特殊字符)。

您可以查阅Go的JSON包文档,了解有关编组和解组步骤的更多详细信息。

英文:

Generally, encoding/decoding JSON refers to the process of actually reading/writing the character data to a string or binary form. Marshaling/Unmarshaling refers to the process of mapping JSON types from and to Go data types and primitives.

Actual encoding can include things like serializing unicode characters for example. I think they may be used somewhat interchangeably in documentation sometimes because they generally occur in the same step. The Marshal function for example, will determine which JSON type to marshal something to, and then it will be encoded in string form (which may include other details such as special characters if its textual data).

You can consult the go json package docs for more details on how the marshaling/unmarshaling steps work.

答案3

得分: 16

JSON的编码/解码和JSON的编组/解组之间有什么区别?

编组(Marshaling)和编码(Encoding)是不同的概念,可以在维基百科(或其他地方)上找到更详细的解释。简而言之,对象被编组为JSON编码的字符串。

不要让Golang中的json.NewEncoder / (json.Encoder).Encodejson.Marshal方法让你困惑。它们都将对象编组为JSON编码的字符串。区别在于Encoder首先将对象编组为JSON编码的字符串,然后将该数据写入缓冲流(或数据缓冲区)。因此,Encoder使用的代码和内存开销比简单的json.Marshal更多。

你可以在Golang的源代码中看到这一点:

通常,如果你需要将JSON编码的字符串发送到文件系统或作为HTTP响应,可能需要使用缓冲流。然而,你也可以使用管道(pipe)在没有缓冲流的情况下发送这个JSON编码的字符串。

英文:

> What is the difference between JSON 'encoding/decoding' and JSON 'marshalling/unmarshalling'?


Marshaling and Encoding are of course different concepts, better addressed on Wikipedia (or elsewhere). But in short, objects are marshaled into JSON encoded strings.

Also don't let the Golang json.NewEncoder / (json.Encoder).Encode and json.Marshal methods confuse you. They both marshal objects into JSON encoded strings. The difference being the Encoder, first marshals the object to a JSON encoded string, then writes that data to a buffer stream (or Data Buffer on Wikipedia). The Encoder therefore, uses more code and memory overhead than the simpler json.Marshal.

You can also see this in the Golang source code:

Typically, if you need to send the JSON encoded string to a file system, or as an HTTP response, you may need the use of a buffer stream. However, you can also send this JSON encoded string without a buffer stream using a pipe.

答案4

得分: 0

func Encode是Encoder上的一个方法,它将JSON编码的Go类型写入输出流(func NewEncoder接受一个io.Writer并返回*Encoder)。

你的Go类型进入黑盒子,并以JSON格式写入流中。

Marshal是一个函数,返回Go类型的JSON编码。

在这里,你的Go类型进入黑盒子,并以JSON格式从盒子中出来。

它在以下网址有详细的文档:
golang.org/pkg/encoding/json/

英文:

func Encode is a method on an Encoder, which writes JSON encoded Go types to an output stream (func NewEncoder takes an io.Writer and returns a *Encoder).

Your Go types enter the black box and are written out to the stream in JSON formatting.

Marshal is a function that returns JSON encoding of Go types.

Here your Go types enter the black box and come out of the box in JSON formatting.

It's well documented at:
golang.org/pkg/encoding/json/

答案5

得分: 0

这些方法之间并没有太大的区别,更多取决于你的使用方式。如果你有一个io.Reader(例如:当你使用HTTP或文件系统时),使用NewDecoder会更容易:

在Golang中,JSON编码和编组之间有什么区别?

它接受io.Reader并返回*Decoder类型,然后你可以链式调用Decode方法:

在Golang中,JSON编码和编组之间有什么区别?

这个Decode方法会将数据写入你作为参数传递给它的v中。

另一方面,

Unmarshal方法可以帮助你轻松地将字符串化的JSON转换为Go数据类型(主要是结构体和映射)。

在Golang中,JSON编码和编组之间有什么区别?

更多详细信息,请阅读文档:

https://golang.org/pkg/encoding/json/#Unmarshal

https://golang.org/pkg/encoding/json/#NewDecoder

https://golang.org/pkg/encoding/json/#Decoder.Decode

英文:

There is not a lot of difference between these methods, it's more depends on your usage,
If you have io.Reader (for example: when you are working with HTTP or file system), it's easier to use NewDecoder:

在Golang中,JSON编码和编组之间有什么区别?

It gives io.Reader and returns *Decoder type,
then you chain a Decode method to it:

在Golang中,JSON编码和编组之间有什么区别?

And this Decode method will write data to v that you passed to it as a parameter.

On the other hand

Unmarshal method will help you easily convert stringified JSON to Go data types (mostly structs and maps)

在Golang中,JSON编码和编组之间有什么区别?

for more details, you can read the documentation:

https://golang.org/pkg/encoding/json/#Unmarshal

https://golang.org/pkg/encoding/json/#NewDecoder

https://golang.org/pkg/encoding/json/#Decoder.Decode

答案6

得分: 0

虽然有一些好的答案,但我想总结一下编码/解码编组/解组之间的区别,如下所示。在某些情况下,您可以使用编码/解码,否则可以使用编组/解组

  • 编码/解码 JSON 是指实际将字符数据读取/写入字符串或二进制形式的过程。

    • 在处理请求或响应体时,请使用NewEncoder,因为它们是Reader,这样可以节省将其转换为字节数组以与Marshal一起使用的步骤。
    • 编码器还提供了一些额外的控制,例如能够在遇到未知字段时报错,而json.Unmarshal不会这样做。
    • 如果您希望在某些情况下获得缩进的 JSON(例如通过配置),则可以使用SetIndent(true)。此外,json.Encoder还具有SetEscapeHTML选项。
  • 编组/解组是指将 JSON 类型映射到 Go 数据类型和基本类型,以及从 Go 数据类型和基本类型映射到 JSON 类型。

来源 1 2

英文:

Although there are some good answers for it. I would like to summarize the difference between Encoding/decoding and Marshaling/Unmarshaling as below. Also some cases, you may use Encoding/decoding, otherwise, Marshaling/Unmarshaling could be used.

  • Encoding/decoding JSON refers to the process of actually reading/writing the character data to a string or binary form.

    • Use NewEncoder when working with request or response bodies since they are Readers and it saves you a step of turning it into a byte array to use with Marshal
    • The encoder also gives you some additional control like being able to error on unknown fields, which json.Unmarshal does not do.
    • If you want indented JSON in some cases (by configurations, for example), then you can SetIndent(true). Also, the json.Encoder has SetEscapeHTML option
  • Marshaling/Unmarshaling refers to mapping JSON types from and to Go data types and primitives.

Source 1 2

huangapple
  • 本文由 发表于 2015年10月11日 11:02:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/33061117.html
匿名

发表评论

匿名网友

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

确定