简体   繁体   中英

how to store protocol buffer's “oneof” field with json

I want to my protobuf's message object to json for save/load to redis. but oneof field don't work as expected.

  • test.proto

simple oneof example.

syntax = "proto3";

message example {
    oneof test {
        bool one = 1;
        bool two = 2;
    }
}
  • Makefile

how to build the protobuf code into 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

how I marshaled/unmarshaled my example object.

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

then, the result is

$ 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

anyone know the reason?

Thanks to Peter, I could encode my message to json.

protojson document

  • my protoc environment
// versions:
//  protoc-gen-go v1.25.0-devel
//  protoc        v3.6.

my answer code

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

and the result

$ go run main.go
{{{} [] [] <nil>} 0 [] 0xc0000141cc}
before one:  true
before two:  false
{"one":true}
-----
{{{} [] [] 0xc0001203c0} 0 [] 0xc000014253}
after one:  true
after two:  false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM