使用 json.Unmarshal 与 json.NewDecoder.Decode 解码 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21197239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Decoding JSON using json.Unmarshal vs json.NewDecoder.Decode
提问by Simone Carletti
I'm developing an API client where I need to encode a JSON payload on request and decode a JSON body from the response.
我正在开发一个 API 客户端,我需要根据请求对 JSON 有效负载进行编码,并从响应中解码 JSON 正文。
I've read the source code from several libraries and from what I have seen, I have basically two possibilities for encoding and decoding a JSON string.
我已经阅读了几个库的源代码,从我所看到的,我基本上有两种编码和解码 JSON 字符串的可能性。
Use json.Unmarshalpassing the entire response string
使用json.Unmarshal传递整个响应字符串
data, err := ioutil.ReadAll(resp.Body)
if err == nil && data != nil {
err = json.Unmarshal(data, value)
}
or using json.NewDecoder.Decode
或使用 json.NewDecoder.Decode
err = json.NewDecoder(resp.Body).Decode(value)
In my case, when dealing with HTTP responses that implements io.Reader, the second version seems to be require less code, but since I've seen both I wonder if there is any preference whether I should use a solution rather than the other.
就我而言,在处理实现 的 HTTP 响应时,io.Reader第二个版本似乎需要较少的代码,但由于我已经看过两者,我想知道是否应该使用解决方案而不是其他解决方案有任何偏好。
Moreover, the accepted answer from this questionsays
此外,这个问题的公认答案说
Please use
json.Decoderinstead ofjson.Unmarshal.
请使用
json.Decoder代替json.Unmarshal。
but it didn't mention the reason. Should I really avoid using json.Unmarshal?
但它没有提到原因。我真的应该避免使用json.Unmarshal吗?
回答by James Henstridge
It really depends on what your input is. If you look at the implementation of the Decodemethod of json.Decoder, it buffers the entire JSON value in memory before unmarshalling it into a Go value. So in most cases it won't be any more memory efficient (although this could easily change in a future version of the language).
这真的取决于你的输入是什么。如果您查看Decode方法的实现json.Decoder,它会在将整个 JSON 值解组为 Go 值之前缓冲内存中的整个 JSON 值。因此,在大多数情况下,它的内存效率不会更高(尽管在该语言的未来版本中这很容易改变)。
So a better rule of thumb is this:
所以一个更好的经验法则是这样的:
- Use
json.Decoderif your data is coming from anio.Readerstream, or you need to decode multiple values from a stream of data. - Use
json.Unmarshalif you already have the JSON data in memory.
- 使用
json.Decoder,如果你的数据从一个即将io.Reader流,或者需要多个值,从数据流进行解码。 json.Unmarshal如果内存中已有 JSON 数据,请使用。
For the case of reading from an HTTP request, I'd pick json.Decodersince you're obviously reading from a stream.
对于从 HTTP 请求读取的情况,我会选择,json.Decoder因为您显然是从流中读取。

