我想要我的protobuf的消息对象json保存/加载到redis。但其中一个领域不像预期的那样工作。
简单的例子。
syntax = "proto3";
message example {
oneof test {
bool one = 1;
bool two = 2;
}
}如何将原始代码构建为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 我如何封送/解封我的示例对象。
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有人知道原因吗?
发布于 2020-08-23 13:56:32
多亏了彼得,我才能把我的信息编码给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: falsehttps://stackoverflow.com/questions/63545226
复制相似问题