golang / protobuf

Go support for Google's protocol buffers

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

protojson: Add UnmarshalOption to convert unix timestamp(int64) to google.protobuf.Timestamp

sorcererxw opened this issue · comments

Is your feature request related to a problem? Please describe.

Currently, when using protojson to unmarshal JSON data into google.protobuf.Timestamp fields, protojson only accept ISO8601 string. This requires additional code to perform the conversion, which can be tedious and error-prone.

Describe the solution you'd like

I would like to request the addition of a new UnmarshalOption to protojson that would automatically convert Unix timestamps encoded as integers to google.protobuf.Timestamp types. This would simplify the process of unmarshaling JSON data that contains Unix timestamps and improve the usability of protojson in situations where Unix timestamps are commonly used.

The UnmarshalOption could have a function field named ConvertTimestamp. ConvertTimestamp accepts a int64 value and allows user to convert the value to time.Time. The int64 value could represent Unix time in seconds/milliseconds/nanoseconds, etc. It could be used as follows:

opts := protojson.UnmarshalOptions{
    UseProtoNames: true,
    ConvertTimestamp: func(val int64) time.Time { return time.Unix(val,0) },
}

When the ConvertTimestamps option is set, protojson would automatically convert any integer values in the JSON data that represent Unix timestamps to google.protobuf.Timestamp types.

Additional context

This feature would greatly improve the usability of protojson in situations where Unix timestamps are commonly used. Thank you for considering this feature request!

Currently, the proto3 JSON mapping standards are the authority about how google.protobuf.Timestamps are to be encoded: https://protobuf.dev/programming-guides/proto3/#json

Uses RFC 3339, where generated output will always be Z-normalized and uses 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted.

Any deviation from the standard must be coördinated with the larger project to ensure cross-language compatibility. So, my recommendation here is to file a feature request issue with https://github.com/protocolbuffers/protobuf/issues and once incorporated into the standard, then it would be something we could adopt.