golang json解码的坑

2019-06-08  本文已影响0人  golang推广大使

go语言中有个大坑,那就json反序列化的坑。下面的代码给出示例和解决办法:

package main

import (
    "bytes"
    "log"
    "time"

    "github.com/json-iterator/go"
)

type Info struct {
    Id int
}

func Log(format string, args ...interface{}) {
    log.Printf(format+"\n", args...)
}
func main() {
    log.SetFlags(log.Ldate | log.Lshortfile) //
    m := make(map[string]interface{})
    i := Info{
        Id: int(time.Now().UnixNano()),
    }
    json := jsoniter.ConfigCompatibleWithStandardLibrary
    data, _ := json.Marshal(i)
    json.Unmarshal(data, &m)
    Log("m is:%+v", m)

    dec := json.NewDecoder(bytes.NewBuffer(data))
    dec.UseNumber()
    dec.Decode(&m)

    Log("usenumber m is:%+v", m)
    dec = json.NewDecoder(bytes.NewBuffer(data))
    dec.Decode(&m)
    Log("m is:%+v", m)

}

上一篇下一篇

猜你喜欢

热点阅读