Converting Protocol Buffers Messages to and from JSON in Go: Difference between revisions
Jump to navigation
Jump to search
(No difference)
|
Latest revision as of 23:05, 8 May 2024
Internal
Overview
This example uses this message definition:
message SomeMessage {
int32 id = 1;
bool is_valid = 2;
string name = 3;
repeated string sample_list = 4;
}
The Go code is generated following the instructions from:
To and From JSON
import (
"fmt"
"strings"
"example.com/blue/pkg/somepkgpb"
"github.com/golang/protobuf/jsonpb"
)
sm := &somepkgpb.SomeMessage{
Id: 1,
IsValid: true,
Name: "something",
SampleList: []string{"a", "b", "c"},
}
jsonMarshaler := &jsonpb.Marshaler{}
s, err := jsonMarshaler.MarshalToString(sm)
if err != nil { ... }
fmt.Printf("JSON representation: %s\n", s)
sm2 := &somepkgpb.SomeMessage{}
jsonUnmarshaler := &jsonpb.Unmarshaler{}
err = jsonUnmarshaler.Unmarshal(strings.NewReader(s), sm2)
if err != nil { ... }