Home >Backend Development >Golang >How to Decode a JSON with Non-Primitive Fields into Protobuf in Go?

How to Decode a JSON with Non-Primitive Fields into Protobuf in Go?

DDD
DDDOriginal
2024-10-28 22:50:30839browse

How to Decode a JSON with Non-Primitive Fields into Protobuf in Go?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn