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)
}

iPhone – Convert NSMutableData to ios JSON object and parse the data

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self.responseData length];
//convert to json
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:nil];

//show all values
for (id key in dic) {
id value = [dic objectForKey:key];
NSString *keyAsString = (NSString *)key;
NSString *valueAsString = (NSString *)value;

NSLog(@"key: %@", keyAsString);
NSLog(@"value: %@", valueAsString);
}

NSArray *results = [dic objectForKey:@"results"];
for (NSDictionary *result in results) {
NSString *name = [result objectForKey:@"name"];

[nameList addObject:name];
NSLog(@"Name : %@", name);
}