Decoding JSON to Protobuf with Non-Primitive Fields
The issue arises when trying to unmarshal a JSON containing a non-primitive field, like Data in this case, into a Protobuf using the "encoding/json" library. The default behavior of the library is not able to properly handle these fields, resulting in them being set to nil.
Using Protobuf Encoding/Protojson
To correctly handle non-primitive fields, you should utilize the google.golang.org/protobuf/encoding/protojson library. This library provides specialized decoding functions for Protobuf messages.
The corrected code to decode the JSON into the Protobuf would be:
req := &proto.JobCreateRequest{} err := protojson.Unmarshal(bytes, req)
This approach ensures that the Data field is deserialized and initialized correctly. It recursively traverses the JSON structure and attempts to assign values to all fields defined in the Protobuf message.
The above is the detailed content of How to Decode a JSON with Non-Primitive Fields into Protobuf in Go?. For more information, please follow other related articles on the PHP Chinese website!