golang / protobuf

Go support for Google's protocol buffers
BSD 3-Clause "New" or "Revised" License
9.74k stars 1.58k forks source link

how to use protojson to unmarshal json with lowerCamelCase fields #1508

Closed horacimacias closed 1 year ago

horacimacias commented 1 year ago

Is your feature request related to a problem? Please describe. Yes. Related to unmarshaling json that was produced by marshaling a protobuf message.

Describe the solution you'd like I'd like to be able to unmarshal json with the same level of flexibility I have when marshaling. For example, I have an instance of User and I marshal it using UseProtoNames: false which should result in lowerCamelCase name in JSON field names. I'm expecting to be able to take that json and use protojson to Unmarshal and get a valid User back.

So far, I get an unknown field error when using protojson.Unmarshal

Describe alternatives you've considered Using other json marshal/unmarshal modules such as encoding/json or jsonpb

Additional context I believe UnmarshalOptions should have the same flags MarshalOptions has.

puellanivis commented 1 year ago

There is no need for such an option. Proto3 JSON standards already require the unmarshaller to accept both the converted lowerCamelCase† and proto_field_name.

Proto3 JSON parsers are required to accept both the converted lowerCamelCase name and the proto field name. https://developers.google.com/protocol-buffers/docs/proto3#json

†: N.B.: this is the “converted lowerCamelCase” name, which is not necessarily itself actually lowerCamelCase if it started with a capital letter.

horacimacias commented 1 year ago

thanks. Perhaps I'm also seeing another side effect of https://github.com/golang/protobuf/issues/1507 on which the json produced from a protobuf message not using snake_case ends up being non-unmarshalable. I'll update my protos based on 1507 feedback and see if this is still an issue.