其他分享
首页 > 其他分享> > go基于结构的数据序列和还原

go基于结构的数据序列和还原

作者:互联网

go基于结构的数据序列和还原

// test2 project main.go
package main

import (
	"encoding/json"
	"fmt"

	"github.com/golang/protobuf/proto"
)

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 _, 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 _, v := range ss.Tunits {
		fmt.Println(v.Unitname)
	}
}

  

标签:Println,dws,fmt,Unitid,序列,json,还原,Tunits,go
来源: https://www.cnblogs.com/hnxxcxg/p/16502774.html