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
Release: 2024-10-28 22:50:30
Original
837 people have browsed it

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template