zoukankan      html  css  js  c++  java
  • protobuf序列化

    package main
    
    import (
    	"fmt"
    	"github.com/gogo/protobuf/jsonpb"
    	"github.com/golang/protobuf/proto"
    	"io/ioutil"
    	"log"
    	"test/src/first"
    )
    
    
    func main() {
    	person := newPersonMessage()
    	//fmt.Println(person.GetUsername())
    	//_ = writeToFile("person.bin", person)
    
    	//pm := first.PersonMessage{}
    	//
    	//_ = readFromFile("person.bin",&pm)
    
    	fmt.Println(&person)
    
    	jsonstr := toJson(person)
    	fmt.Println(jsonstr)
    
    	pm3 := first.PersonMessage{}
    	_ = fromJson(jsonstr,&pm3)
    	fmt.Println(&pm3)
    
    }
    
    func toJson(pm proto.Message)  string {
    	marshaler := jsonpb.Marshaler{Indent: "    "}
    	str,err := marshaler.MarshalToString(pm)
    	if err != nil{
    		log.Fatalln("转换失败")
    	}
    
    	return str
    
    }
    
    func fromJson(in string,pb proto.Message) error  {
    	err := jsonpb.UnmarshalString(in,pb); if err!=nil{
    		log.Fatalln("失败")
    	}
    
    	return nil
    }
    
    func readFromFile(filename string,pb proto.Message) error  {
    	dateBytes,err := ioutil.ReadFile("./person.bin"); if err!=nil{
    		log.Fatalln("读取失败")
    	}
    
    	err =proto.Unmarshal(dateBytes,pb)
    	if err!=nil{
    		log.Fatalln("序列化失败")
    	}
    
    	return nil
    }
    
    
    func writeToFile(filename string,pb proto.Message) error  {
    	data,error := proto.Marshal(pb)
    	if error !=nil{
    		log.Fatalln("无法序列化到bytes")
    	}
    
    	if err := ioutil.WriteFile(filename,data,0644); err !=nil{
    		log.Fatalln("无法写入到文件")
    	}
    	log.Println("写入成功")
    	return nil
    }
    
    func newPersonMessage() * first.PersonMessage  {
    
    	p := first.PersonMessage{
    		Id:       1,
    		Username: "hello",
    	}
    	return &p
    }
    
  • 相关阅读:
    几道关于this的经典练习题的理解与分析
    对this的理解与总结
    内存机制及内存泄漏相关总结
    css3-伪元素与伪类
    css3-目标伪类选择器:target的应用
    react学习资料
    angular2学习视频
    vue学习资料
    gulp 入门---使用gulp压缩图片
    gulp 入门---使用gulp压缩css
  • 原文地址:https://www.cnblogs.com/brady-wang/p/14442598.html
Copyright © 2011-2022 走看看