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


  • 相关阅读:
    C#读写XML no
    ComboBox、ListBox绑定和获取数据 no
    win7 安装oracle 11g no
    2011没有惊天动地 no
    Oracle 删除重复数据只留一条 no
    Oracle 创建用户并分配权限 no
    Oracle 导出、导入某用户所有数据(包括表、视图、存储过程...) no
    谢谢,博客园这么快就审批通过了我的申请!
    Eclipse 中 JAVA AWT相关包不提示问题(解决)
    Eclipse java项目转Maven项目
  • 原文地址:https://www.cnblogs.com/unqiang/p/12198588.html
Copyright © 2011-2022 走看看