go基于结构的数据序列和还原
go基于结构的数据序列和还原
csharp;gutter:true;
// test2 project main.go
package main</p>
<p>import (
"encoding/json"
"fmt"</p>
<pre><code>"github.com/golang/protobuf/proto"
</code></pre>
<p>)</p>
<p>func main() {
var dw Tunit
dw.Unitid = "1"
dw.Unitname = "个"
var dw2 Tunit
dw2.Unitid = "2"
dw2.Unitname = "双"
var dws TunitArray
dws.Tunits = append(dws.Tunits, &dw)
dws.Tunits = append(dws.Tunits, &dw2)
//json序列
b, _ := json.Marshal(dws)
fmt.Println(string(b)) //{"UnitsArr":[{"Unitid":"1","Unitname":"个"},{"Unitid":"2","Unitname":"双"}]}
//json还原
var s TunitArray
json.Unmarshal(b, &s)
fmt.Println(s)
for <em>, v := range s.Tunits {
fmt.Println(v.Unitid)
}
//protobuf序列
b2, _ := proto.Marshal(&dws)
fmt.Println(string(b2))
//protobuf还原
var ss TunitArray
proto.Unmarshal(b2, &ss)
fmt.Println(ss)
for </em>, v := range ss.Tunits {
fmt.Println(v.Unitname)
}
}
Original: https://www.cnblogs.com/hnxxcxg/p/16502774.html
Author: delphi中间件
Title: go基于结构的数据序列和还原
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/546010/
转载文章受原作者版权保护。转载请注明原作者出处!