如何解决如何使用json
我想将我的protobuf的消息对象保存为json以保存/加载到redis。 但是其中一个字段不能按预期工作。
- test.proto
一个简单的例子。
syntax = "proto3";
message example {
oneof test {
bool one = 1;
bool two = 2;
}
}
- Makefile
如何将protobuf代码构建到golang中。
.PHONY: proto
proto:
protoc -Iproto/ -I/usr/local/include \
-I$(GOPATH)/src \
-I$(GOPATH)/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/ \
--go_out=plugins=grpc:proto \
proto/test.proto
- main.go
我如何封送/解封示例对象。
package main
import (
"encoding/json"
"fmt"
pb "test/proto"
)
func main() {
fmt.Println()
obj := pb.Example{Test: &pb.Example_One{true}}
fmt.Println(obj)
fmt.Println("before one: ",obj.GetOne())
fmt.Println("before two: ",obj.GetTwo())
jsonData,_ := json.Marshal(obj)
fmt.Println(string(jsonData))
fmt.Println("-----")
obj2 := pb.Example{}
_ = json.Unmarshal(jsonData,&obj2)
fmt.Println(obj2)
fmt.Println("after one: ",obj2.GetOne())
fmt.Println("after two: ",obj2.GetTwo())
}
然后,结果是
$ go run main.go
{{{} [] [] <nil>} 0 [] 0xc0000141a0}
before one: true
before two: false
{"Test":{"One":true}}
-----
{{{} [] [] <nil>} 0 [] <nil>}
after one: false
after two: false
有人知道原因吗?
解决方法
感谢Peter,我可以将消息编码为json。
- 我的协议环境
// versions:
// protoc-gen-go v1.25.0-devel
// protoc v3.6.
我的答案代码
package main
import (
"fmt"
pb "test/proto"
"google.golang.org/protobuf/encoding/protojson"
)
func main() {
obj := pb.Example{Test: &pb.Example_One{true}}
fmt.Println(obj)
fmt.Println("before one: ",obj.GetOne())
fmt.Println("before two: ",obj.GetTwo())
jsonData,_ := protojson.Marshal(&obj)
fmt.Println(string(jsonData))
fmt.Println("-----")
obj2 := pb.Example{}
_ = protojson.Unmarshal(jsonData,&obj2)
fmt.Println(obj2)
fmt.Println("after one: ",obj2.GetOne())
fmt.Println("after two: ",obj2.GetTwo())
}
和结果
$ go run main.go
{{{} [] [] <nil>} 0 [] 0xc0000141cc}
before one: true
before two: false
{"one":true}
-----
{{{} [] [] 0xc0001203c0} 0 [] 0xc000014253}
after one: true
after two: false
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。