Justin Thomas
Justin Thomas

Reputation: 5848

ProtoBuf Unmarshal JSON into Timestamp

Trying to see if something like this exists:

message TimestampedThing {

    string thing = 1;
    Timestamp date = 2 (layout="2018-03-07T01:00:00.000Z");
}

Getting a parse error when I unmarshal it into the GRPC object.

details: 'json: cannot unmarshal string into Go struct field TimestampedThing.createdTimestamp of type timestamp.Timestamp'

Upvotes: 3

Views: 6500

Answers (3)

sensazn
sensazn

Reputation: 48

Update: Use protojson as google.golang.org/protobuf has been deprecated

See: https://pkg.go.dev/google.golang.org/protobuf/encoding/protojson#Unmarshal

Backpacking off Justins response ->

    protojson.Unmarshal(data []byte, msg protoreflect.ProtoMessage{})

Upvotes: 1

Justin Thomas
Justin Thomas

Reputation: 5848

Turns out I needed jsonpb: https://godoc.org/github.com/golang/protobuf/jsonpb

jsonpb.Unmarshal(bufio.NewReader(bytes), &pb.TimestampedThing)

Upvotes: 2

Yatin Goyal
Yatin Goyal

Reputation: 342

Timestamp in protobuf is wellknown type(consists of seconds and nanos) that is represented in the ISO format, this is taken care in JSONFormat class.

Representation of Timestamp

message Timestamp{
  int64 seconds,
  int32 nanos
}

Layout is no keyword in protobuf and as far as i know there is no option to define layout/format for Timestamp.

Upvotes: 1

Related Questions