Howto marshal an instance of protobuf to JSON

Proto

syntax = "proto3";

package myproto;

message MyMessage {
    string name = 1;
    int32 age = 2;
}

package main

import (
    "fmt"
    "github.com/golang/protobuf/jsonpb"
    "github.com/golang/protobuf/proto"
    "myproto" // Import the generated protobuf package
)

func main() {
    // Create an instance of MyMessage
    myMessage := &myproto.MyMessage{
        Name: "Alice",
        Age:  30,
    }

    // Create a JSON marshaler
    marshaller := &jsonpb.Marshaler{}

    // Marshal the protobuf message to JSON
    jsonString, err := marshaller.MarshalToString(myMessage)
    if err != nil {
        fmt.Println("Error marshaling to JSON:", err)
        return
    }

    // Print the JSON string
    fmt.Println(jsonString)
}

How to unmarshal protobuf to json in golang

package main

import (
	"encoding/json"
	"fmt"
)

// Define a struct
type SomeStruct struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
}

func main() {
	jsonString := `{
        "id": 1,
        "title": "Some title"
    }`

	var item SomeStruct

	// Unmarshal the JSON data into the struct
	if err := json.Unmarshal([]byte(jsonString), &item); err != nil {
		fmt.Println("Error unmarshaling content:", err)
		return
	}

	fmt.Println("ID:", item.ID)
	fmt.Println("Title:", item.Title)
}