golang json

原文链接: golang json

1. Decode 和 Unmarshal 区别


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)

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 tags

"web": ":50052",
"cpu": "1",
"cache": [{"host": "", "port": 3000},{"host": "", "port": 3000}],
"ns" : "visitor",

type Config struct {
	Cpu    int    `json:"cpu,string"`   // 结构体中是int 但是json中是string类型
	Web    string `json:"web"`          // 绑定json字段
	Rpc    string `json:"-"`            // 忽略字段解析 双向
	Ns     string                       // 等价 `json:"ns"`
	Set    string
	Cache  []ServerCache `json:"caches,omitempty"` //有就解析没有就不解析
	Logger GrayLog
c := new(Config)
file, _ := os.Open("conf.json")
err = json.NewDecoder(file).Decode(&c)