Protocol Buffers和JSON相互转换
下载安装protojson
go get google.golang.org/protobuf/encoding/protojson
创建protobuf消息
syntax = "proto3";
option go_package = "./;blog";
package blog;
message User{
int32 uid =1;
string uname = 2;
int32 age = 3;
}
message Article{
int32 aid = 1;
string title = 2;
int32 views = 3;
};
编译生成go文件
protoc --go_out=./blog ./blog/*.proto
创建main.go文件
package main
import (
"fmt"
"pro02/blog"
"google.golang.org/protobuf/encoding/protojson"
)
func main() {
article := &blog.Article{
Aid: 1,
Title: "protobuf for golang",
Views: 100,
}
// message 转换成 json
jsonString := protojson.Format(article.ProtoReflect().Interface())
fmt.Printf("jsonString: %v\n", jsonString)
// json 转换成 message
message := article.ProtoReflect().Interface()
protojson.Unmarshal([]byte(jsonString), message)
fmt.Printf("m: %v\n", message)
}
运行结果:
[Running] go run "e:\golang开发学习\protobuffer\src\pro02\main.go"
jsonString: {
"aid": 1,
"title": "protobuf for golang",
"views": 100
}
m: aid:1 title:"protobuf for golang" views:100
[Done] exited with code=0 in 1.435 seconds