zoukankan      html  css  js  c++  java
  • go的json序列化和反序列化

    go的序列化和反序列化的原生和插件比较多,这里使用一个 json-iterator

    示例如下:

    package main
    
    import (
        //"encoding/json"
        "fmt"
        "github.com/json-iterator/go"
    )
    
    func main() {
                 jjson()
    }
    
    
    func jjson() {
        var jsonBlob = []byte(`[
            {"Name": "张三", "Order": "Monotremata"},
            {"Name": "李四",    "Order": "Dasyuromorphia"}
        ]`)
        type Animal struct {
            Name  string
            Order string
        }
    
        var animals []Animal
        var json_iterator = jsoniter.ConfigCompatibleWithStandardLibrary
        json_iterator.Unmarshal(jsonBlob, &animals)
        fmt.Printf("animals...Unmarshal....%+v", animals)
    
        b := Json(animals)
        fmt.Printf("b....Marshal...", string(b))
    }
    
    func Json(i interface{}) []byte {
    
        var json_iterator = jsoniter.ConfigCompatibleWithStandardLibrary
        outi, err := json_iterator.Marshal(i)
        if err != nil {
            fmt.Println("WriteFile...JsonMarshal...error.....:", err)
        }
        return outi
    }    

    相关地址:

    https://github.com/json-iterator/go

    官方benchmark 测试如下:

    自测对比顺序

    序列化
    json.Marshal(data)
    jsoniter.Marshal(data)
    反序列化
    json.Unmarshal([]byte(str), &Msg)
    jsoniter.Unmarshal([]byte(str), &Msg)

    1、1000个时间消耗

    序列化
    time cost = 4.0002ms
    time cost = 3.0002ms
    反序列化
    time cost = 15.0008ms
    time cost = 4.0003m

    2、10000个时间消耗

    序列化
    time cost = 36.0021ms
    time cost = 22.0013ms
    反序列化
    time cost = 145.0083ms
    time cost = 39.0022ms

    3、100000个时间消耗

    序列化
    time cost = 351.02ms
    time cost = 237.0136ms
    反序列化
    time cost = 1.4610835s
    time cost = 392.0225ms

    1、1000000个时间消耗

    序列化
    time cost = 3.4391967s
    time cost = 2.3011316s
    反序列化
    time cost = 14.4888287s
    time cost = 3.863221s


  • 相关阅读:
    cvsmooth平滑处理函数
    对图像频率的一些理解
    VIM 如何切换buffer
    Mplab X IDE 安装DMCI
    测试 使用橘子曰
    wlr设置 Blog Ping
    wlr快捷键
    使用Windows Live Writer写文章时不要用360清除垃圾
    如何将Windows live writer草稿转存到其他电脑上
    使用windows live writer写cnblog-1 安装wlr
  • 原文地址:https://www.cnblogs.com/unqiang/p/12198588.html
Copyright © 2011-2022 走看看