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)
	}
}

  

posted @ 2022-07-21 17:26  delphi中间件  阅读(49)  评论(0编辑  收藏  举报