Skip to content

Instantly share code, notes, and snippets.

@PxyUp
Last active May 22, 2020 00:43
Show Gist options
  • Save PxyUp/373565bc466193a98bed809c9cd50431 to your computer and use it in GitHub Desktop.
Save PxyUp/373565bc466193a98bed809c9cd50431 to your computer and use it in GitHub Desktop.
Unmarshal/Marshal github.com/golang/protobuf/ptypes/struct
package marshal
import (
"bytes"
"github.com/golang/protobuf/jsonpb"
structType "github.com/golang/protobuf/ptypes/struct"
"github.com/stretchr/testify/assert"
"testing"
)
/*
MUCH BUTTER AND SIMPLE
import "google.golang.org/protobuf/encoding/protojson"
protojson.Marshal(m proto.Message) ([]byte, error)
protojson.Unmarshal(b []byte, m proto.Message) error
*/
func TestMarshal(t *testing.T) {
t.Run("test marshal", func(t *testing.T) {
value := &structType.Value{
Kind: &structType.Value_ListValue{
ListValue: &structType.ListValue{
Values: []*structType.Value{
{
Kind: &structType.Value_StringValue{
StringValue: "2012-04-23T18:25:43Z",
},
},
{
Kind: &structType.Value_NumberValue{
NumberValue: float64(31),
},
},
},
},
},
}
b := bytes.Buffer{}
err := (&jsonpb.Marshaler{}).Marshal(&b, value)
assert.Nil(t, err)
str := &structType.Value{}
err = jsonpb.Unmarshal(bytes.NewReader(b.Bytes()), str);
assert.Nil(t, err)
assert.Equal(t, value, str)
})
}
@puellanivis
Copy link

puellanivis commented May 21, 2020

Use assert.NoError(t, err) to more strongly assert conditions than just assert.Nil.

Not so sure why you convert the bytes.Buffer to a bytes.Reader when it’s already an io.Reader.

@PxyUp
Copy link
Author

PxyUp commented May 22, 2020

@puellanivis thanks, i think i make typo, today i found more correct solution:

import "google.golang.org/protobuf/encoding/protojson"

protojson.Marshal(m proto.Message) ([]byte, error)
protojson.Unmarshal(b []byte, m proto.Message) error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment