使用json.Unmarshal与json.NewDecoder.Decode解码JSON [英] Decoding JSON using json.Unmarshal vs json.NewDecoder.Decode

查看:416
本文介绍了使用json.Unmarshal与json.NewDecoder.Decode解码JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个API客户端,在该客户端上,我需要根据请求对JSON有效负载进行编码,并从响应中解码JSON正文.

I'm developing an API client where I need to encode a JSON payload on request and decode a JSON body from the response.

我已经从几个库中读取了源代码,并且从我所看到的内容中,我基本上有两种可能性可以对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.Unmarshal 传递整个响应字符串

Use json.Unmarshal passing the entire response string

data, err := ioutil.ReadAll(resp.Body)
if err == nil && data != nil {
    err = json.Unmarshal(data, value)
}

或使用json.NewDecoder.Decode

err = json.NewDecoder(resp.Body).Decode(value)

在我的情况下,当处理实现io.Reader的HTTP响应时,第二个版本似乎需要较少的代码,但是由于我已经看到了两者,所以我想知道是否有任何偏好是应该使用解决方案,而不是使用解决方案?另一个.

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.

此外,该问题的可接受答案

请使用json.Decoder代替json.Unmarshal.

但是没有提到原因.我真的应该避免使用json.Unmarshal吗?

but it didn't mention the reason. Should I really avoid using json.Unmarshal?

推荐答案

这实际上取决于您输入的内容.如果您查看json.DecoderDecode方法的实现,它会在将整个JSON值解组为Go值之前将其存储在内存中.因此,在大多数情况下,内存效率将不再高(尽管在将来的语言版本中很容易改变).

It really depends on what your input is. If you look at the implementation of the Decode method 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).

因此,更好的经验法则是:

So a better rule of thumb is this:

  • 如果您的数据来自io.Reader流,请使用json.Decoder,或者您需要解码数据流中的多个值.
  • 如果内存中已经有JSON数据,请使用json.Unmarshal.
  • Use json.Decoder if your data is coming from an io.Reader stream, or you need to decode multiple values from a stream of data.
  • Use json.Unmarshal if you already have the JSON data in memory.

对于从HTTP请求读取的情况,我选择json.Decoder,因为您显然是从流中读取的.

For the case of reading from an HTTP request, I'd pick json.Decoder since you're obviously reading from a stream.

这篇关于使用json.Unmarshal与json.NewDecoder.Decode解码JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆