使用json.Unmarshal vs json.NewDecoder.Decode解码Golang中的JSON [英] Decoding JSON in Golang using json.Unmarshal vs json.NewDecoder.Decode

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

问题描述

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

代码从几个库和我所看到的,我基本上有两种编码和解码JSON字符串的可能性。



使用 json.Unmarshal 传递整个响应字符串

  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)

在我的情况下,当处理HTTP响应实现 io.Reader ,第二个版本似乎需要更少的代码,但是因为我已经看到了两者,我想知道是否应该使用解决方案比其他。



此外,从这个问题接受的答案


请使用 json.Decoder 代替 json.Unmarshal


但没有提及原因。我真的应该避免使用 json.Unmarshal

解决方案

在你的输入是什么。如果您看看 json.Decoder Decode 方法的实现,它会在内存中缓存整个JSON值将其编组为Go值。所以在大多数情况下,它不会有更高的内存效率(尽管在未来的语言版本中这很容易改变)。

所以一个更好的经验法则是这:


  • 如果您的数据来自于 json.Decoder c $ c> io.Reader 流,或者您需要解码数据流中的多个值。使用 json.Unmarshal

  • 对于从HTTP请求中读取的情况,我会选择 json.Decoder ,因为您显然正在从流中读取数据。


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

    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.

    Use json.Unmarshal passing the entire response string

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

    or using 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.

    Moreover, the accepted answer from this question says

    Please use json.Decoder instead of json.Unmarshal.

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

    解决方案

    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:

    • 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.

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

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

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