Skip to content
This repository was archived by the owner on Dec 15, 2025. It is now read-only.
This repository was archived by the owner on Dec 15, 2025. It is now read-only.

Marshal / Unmarshal - time.Time to timestamppb #694

Open

Description

@go-aegian

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?

Activity

  1. changed the title [-]Marshal / Unmarshal - time.Time to timestamppb[/-] on Feb 15, 2024
  2. changed the title [-]Marshal / Unmarshal - time.Time[/-] on Feb 15, 2024
  3. go-aegian commented on Feb 16, 2024

    @go-aegian
    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions