Last active
May 22, 2020 00:43
-
-
Save PxyUp/373565bc466193a98bed809c9cd50431 to your computer and use it in GitHub Desktop.
Unmarshal/Marshal github.com/golang/protobuf/ptypes/struct
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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
Use
assert.NoError(t, err)
to more strongly assert conditions than justassert.Nil
.Not so sure why you convert the
bytes.Buffer
to abytes.Reader
when it’s already anio.Reader
.