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


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM