Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Marshal / Unmarshal - time.Time to timestamppb #694

Open
go-aegian opened this issue Feb 15, 2024 · 1 comment
Open

Marshal / Unmarshal - time.Time to timestamppb #694

go-aegian opened this issue Feb 15, 2024 · 1 comment

Comments

@go-aegian
Copy link

go-aegian commented Feb 15, 2024

when marshalling a time.Time with either timezone info 2024-03-31T15:09:16.822301-04:00 or without it as Z 2024-03-31T20:09:00.034949Z

the unmarshall throws this error "... readObjectStart: expect { or n, but found ", error found in #10 byte of ..."

How can I resolve this without having to create a custom type for time.Time?

@go-aegian go-aegian changed the title Marshal / Unmarshal - time.Time to timestamppb Marshal / Unmarshal - time.Time Feb 15, 2024
@go-aegian go-aegian changed the title Marshal / Unmarshal - time.Time Marshal / Unmarshal - time.Time to timestamppb Feb 15, 2024
@go-aegian
Copy link
Author

Here is an example of what I'm facing as problem, some others have said to use protojson to unmarshall into a proto message but that is not what I need.


package main

import (
	"fmt"
	"time"
	
	jsoniter "github.com/json-iterator/go"
	"google.golang.org/protobuf/runtime/protoimpl"
	"google.golang.org/protobuf/types/known/timestamppb"
)

type Test struct {
	Id        string    `json:"id,omitempty"`
	ExpiresOn time.Time `json:"expiresOn,omitempty"`
}

type TestPB struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields
	Id            string                 `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
	ExpiresOn     *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=expiresOn,proto3" json:"expiresOn,omitempty"`
}

func main() {
	u := Test{Id: "123", ExpiresOn: time.Now()}
	
	b, err := jsoniter.Marshal(u)
	if err != nil {
		panic(err)
	}
	
	var m TestPB
	err = jsoniter.Unmarshal(b, &m)
	if err != nil {
		panic(err)
	}
	
	fmt.Printf("PB is %v", m)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant