• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

go的json序列化和反序列化

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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


 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
GoRevel-Routing(路由)发布时间:2022-07-10
下一篇:
go gRPC 客户端内存暴涨原因分析 - -见发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap