json-iterator / go

A high-performance 100% compatible drop-in replacement of "encoding/json"
http://jsoniter.com/migrate-from-go-std.html
MIT License
13.33k stars 1.02k forks source link

Marshal / Unmarshal - time.Time to timestamppb #694

Open go-aegian opened 6 months ago

go-aegian commented 6 months ago

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 commented 6 months ago

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)
}