### Get Information Request Example in C#
Source: https://github.com/stefh/protobufjsonconverter/blob/main/PackageReadme.md
Demonstrates how to create a GetInformationRequest and retrieve information asynchronously using the ProtoBufJsonConverter library. Ensure the protoDefinition is correctly set up before use.
```csharp
var protoDefinition = "...". // See above
var request = new GetInformationRequest(protoDefinition);
var response = await _sut.GetInformationAsync(request);
var packageNames = response.PackageNames;
var messageTypes = response.MessageTypes;
var namespaces = response.CSharpNamespaces;
```
--------------------------------
### Proto Definition Example
Source: https://github.com/stefh/protobufjsonconverter/blob/main/PackageReadme.md
Example Protocol Buffers definition file (proto3 syntax) including package name, service definition, and message types.
```proto
syntax = "proto3";
// Package name
package greet;
// The greeting service definition.
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
```
--------------------------------
### Install ProtoBufJsonConverter NuGet Package
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Install the ProtoBufJsonConverter NuGet package using either the .csproj file or the dotnet CLI.
```xml
```
```bash
dotnet add package ProtoBufJsonConverter
```
--------------------------------
### Implement IProtoFileResolver for Virtual File System
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Implement IProtoFileResolver to provide a virtual file system for proto definitions that import other .proto files. This example uses an in-memory dictionary to store proto file contents.
```csharp
using ProtoBufJsonConverter;
using ProtoBufJsonConverter.Models;
// Custom resolver backed by an in-memory dictionary
public class InMemoryProtoFileResolver : IProtoFileResolver
{
private readonly Dictionary _files;
public InMemoryProtoFileResolver(Dictionary files) => _files = files;
public bool Exists(string path) => _files.ContainsKey(path);
public TextReader OpenText(string path) => new StringReader(_files[path]);
}
// -----------------------------------------------
var commonProto =
"""
syntax = "proto3";
package common;
message Address { string city = 1; }
""";
var mainProto =
"""
syntax = "proto3";
import "common.proto";
package user;
message User { string name = 1; common.Address address = 2; }
""";
var resolver = new InMemoryProtoFileResolver(new Dictionary
{
["common.proto"] = commonProto
});
var converter = new Converter(resolver); // global resolver for all requests
var request = new ConvertToJsonRequest(mainProto, "user.User", someBytes)
// OR per-request: .WithProtoFileResolver(resolver)
;
string json = await converter.ConvertAsync(request);
```
--------------------------------
### Blazor Page: Convert ProtoBuf to JSON
Source: https://github.com/stefh/protobufjsonconverter/blob/main/PackageReadme.md
Example Blazor page component demonstrating how to inject IConverter and use it to convert ProtoBuf byte arrays to JSON strings, including options for skipping gRPC headers and writing indented JSON.
```csharp
public partial class Home
{
[Inject]
public required IConverter Converter { get; set; }
private State _state = State.None;
private string _protoDefinition = "..."; // See above
private string _messageType = "greet.HelloRequest";
private ConvertType _selectedConvertType = ConvertType.ToJson;
private string _protobufAsBase64 = "CgRzdGVm";
private bool _skipGrpcHeader = true;
private bool _addGrpcHeader = true;
private string _json = string.Empty;
private async Task OnClick()
{
await ConvertToJsonAsync();
}
private async Task ConvertToJsonAsync()
{
_json = string.Empty;
var bytes = Convert.FromBase64String(_protobufAsBase64);
var convertToJsonRequest = new ConvertToJsonRequest(_protoDefinition, _messageType, bytes)
.WithSkipGrpcHeader(_skipGrpcHeader)
.WithWriteIndented();
_json = await Converter.ConvertAsync(convertToJsonRequest);
}
}
```
--------------------------------
### Blazor WASM Dependency Injection Setup
Source: https://github.com/stefh/protobufjsonconverter/blob/main/PackageReadme.md
Configures dependency injection for ProtoBufJsonConverter in a Blazor WebAssembly application by registering IMetadataReferenceService and IConverter.
```csharp
public class Program
{
public static async Task Main(string[] args)
{
// ...
// Add AddSingleton registrations for the IMetadataReferenceService and IConverter
builder.Services.AddSingleton();
builder.Services.AddSingleton();
await builder.Build().RunAsync();
}
}
```
--------------------------------
### Use CancellationToken for Asynchronous Operations
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
All async methods on IConverter accept an optional CancellationToken for cooperative cancellation. This example demonstrates how to use a CancellationTokenSource to cancel a conversion operation after a specified timeout.
```csharp
using ProtoBufJsonConverter;
using ProtoBufJsonConverter.Models;
var converter = new Converter();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try
{
var request = new ConvertToJsonRequest(protoDefinition, "greet.HelloRequest", bytes);
string json = await converter.ConvertAsync(request, cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Conversion timed out or was cancelled.");
}
```
--------------------------------
### Converter Constructor Overloads
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Demonstrates how to instantiate the Converter class with different configurations, including default, with a custom proto file resolver, and with a fully custom metadata reference service.
```APIDOC
## Converter Constructor Overloads
Instantiate a `Converter` with the default file-system metadata service, an optional `IProtoFileResolver` for multi-file proto schemas, or a fully custom `IMetadataReferenceService` for environments such as Blazor WASM.
```csharp
using ProtoBufJsonConverter;
// Default: uses CreateFromFileMetadataReferenceService (works on .NET / .NET Framework / .NET Standard)
var converter = new Converter();
// With a custom proto file resolver (for multi-file .proto imports)
var resolver = new MyInMemoryProtoFileResolver(); // implements IProtoFileResolver
var converterWithResolver = new Converter(resolver);
// With a fully custom metadata reference service (e.g. Blazor WASM)
// var blazorConverter = new Converter(new BlazorWasmMetadataReferenceService(navigationManager));
```
```
--------------------------------
### Convert Protobuf Any, Struct, ListValue, and StringValue
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Demonstrates the conversion of Protobuf's Any, Struct, ListValue, and StringValue wrapper types. Requires importing the respective proto definitions and using the provided wrapper classes.
```csharp
using ProtoBufJsonConverter;
using ProtoBufJsonConverter.Models;
using ProtoBufJsonConverter.Google.Protobuf.WellKnownTypes;
var protoDefinition =
"""
syntax = "proto3";
import "google/protobuf/wrappers.proto";
import "google/protobuf/any.proto";
import "google/protobuf/struct.proto";
message MyMessageAny { google.protobuf.Any val1 = 1; google.protobuf.Any val2 = 2; }
message MyMessageStruct { google.protobuf.Struct val = 1; }
message MyMessageListValue { google.protobuf.ListValue val = 1; }
message MyMessageStringValue { google.protobuf.StringValue val = 1; }
""" ;
var converter = new Converter();
// --- Any ---
var any1 = Any.Pack(new StringValue { Value = "stef" });
var any2 = Any.Pack(new Int32Value { Value = int.MaxValue });
var anyRequest = new ConvertToProtoBufRequest(protoDefinition, "MyMessageAny", new { val1 = any1, val2 = any2 });
byte[] anyBytes = await converter.ConvertAsync(anyRequest);
string anyJson = await converter.ConvertAsync(new ConvertToJsonRequest(protoDefinition, "MyMessageAny", anyBytes));
// anyJson => {"val1":{"@type":"type.googleapis.com/google.protobuf.StringValue","value":"stef"},
// "val2":{"@type":"type.googleapis.com/google.protobuf.Int32Value","value":2147483647}}
// --- Struct ---
var structObj = new { val = new Struct { Fields = { { "str", new Value("hello") }, { "flag", new Value(true) } } } };
byte[] structBytes = await converter.ConvertAsync(new ConvertToProtoBufRequest(protoDefinition, "MyMessageStruct", structObj));
string structJson = await converter.ConvertAsync(new ConvertToJsonRequest(protoDefinition, "MyMessageStruct", structBytes));
// structJson => {"val":{"fields":{"str":{"string_value":"hello"},"flag":{"bool_value":true}}}}
// --- ListValue ---
var listObj = new { val = new ListValue { Values = { new Value("item1"), new Value(99) } } };
byte[] listBytes = await converter.ConvertAsync(new ConvertToProtoBufRequest(protoDefinition, "MyMessageListValue", listObj));
string listJson = await converter.ConvertAsync(new ConvertToJsonRequest(protoDefinition, "MyMessageListValue", listBytes));
// listJson => {"val":{"values":[{"string_value":"item1"},{"number_value":99.0}]}}
// --- StringValue wrapper ---
var svObj = new { val = "stef" };
byte[] svBytes = await converter.ConvertAsync(new ConvertToProtoBufRequest(protoDefinition, "MyMessageStringValue", svObj));
string svJson = await converter.ConvertAsync(new ConvertToJsonRequest(protoDefinition, "MyMessageStringValue", svBytes));
// svJson => {"val":"stef"}
```
--------------------------------
### Instantiate Converter Class
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Instantiate the `Converter` class. The default constructor uses the file-system metadata service. Provide an `IProtoFileResolver` for multi-file schemas or a custom `IMetadataReferenceService` for environments like Blazor WASM.
```csharp
using ProtoBufJsonConverter;
// Default: uses CreateFromFileMetadataReferenceService (works on .NET / .NET Framework / .NET Standard)
var converter = new Converter();
// With a custom proto file resolver (for multi-file .proto imports)
var resolver = new MyInMemoryProtoFileResolver(); // implements IProtoFileResolver
var converterWithResolver = new Converter(resolver);
// With a fully custom metadata reference service (e.g. Blazor WASM)
// var blazorConverter = new Converter(new BlazorWasmMetadataReferenceService(navigationManager));
```
--------------------------------
### Create MetadataReference using AssemblyDetails
Source: https://github.com/stefh/protobufjsonconverter/blob/main/src-webcil/Readme.md
Shows the process of defining AssemblyDetails and then using the injected IMetadataReferenceService to asynchronously create a MetadataReference.
```csharp
// Define AssemblyDetails
var assemblyDetails = new AssemblyDetails
{
Name = "test"
};
// Call CreateAsync
MetadataReference metadataReference = await service.CreateAsync(assemblyDetails);
```
--------------------------------
### Convert Protobuf Timestamp and Duration (Newer and Legacy Modes)
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Shows conversion of Timestamp and Duration fields. The default mode serializes them as objects with 'seconds' and 'nanos' fields. Legacy mode serializes them as ISO-8601 strings. Ensure the correct `supportNewerGoogleWellKnownTypes` flag is used for legacy mode.
```csharp
using ProtoBufJsonConverter;
using ProtoBufJsonConverter.Models;
var protoDefinition =
"""
syntax = "proto3";
import "google/protobuf/timestamp.proto";
import "google/protobuf/duration.proto";
message MyMessageTimestamp { google.protobuf.Timestamp ts = 1; }
message MyMessageDuration { google.protobuf.Duration du = 1; }
""" ;
var converter = new Converter();
// --- Newer mode (default): object with seconds/nanos fields ---
var objRequest = new ConvertToProtoBufRequest(
protoDefinition,
"MyMessageTimestamp",
new { ts = new { Seconds = 1722301323, Nanos = 12345 } }
// supportNewerGoogleWellKnownTypes: true (default)
);
byte[] bytes = await converter.ConvertAsync(objRequest);
// Convert.ToBase64String(bytes) => "CgkIi/egtQYQjGA="
var jsonRequest = new ConvertToJsonRequest(protoDefinition, "MyMessageTimestamp", bytes);
string json = await converter.ConvertAsync(jsonRequest);
// json => {"ts":{"seconds":1722301323,"nanos":12345}}
// --- Legacy mode: ISO-8601 string ---
var legacyBytes = Convert.FromBase64String("CgYI/orSuwY=");
var legacyRequest = new ConvertToJsonRequest(
protoDefinition, "MyMessageTimestamp", legacyBytes,
supportNewerGoogleWellKnownTypes: false
);
string legacyJson = await converter.ConvertAsync(legacyRequest);
// legacyJson => {"ts":"2024-12-31T23:59:58Z"}
```
--------------------------------
### GetInformationAsync(GetInformationRequest)
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Parses a `.proto` definition and returns package names, C# namespaces, and a mapping of message type names to their compiled .NET `Type`.
```APIDOC
## GetInformationAsync(GetInformationRequest)
### Description
Parses a `.proto` definition and returns the package names, C# namespaces, and a dictionary mapping every fully-qualified message type name to its compiled .NET `Type`. Useful for introspection, tooling, and dynamic dispatch.
### Method
`IConverter.GetInformationAsync`
### Parameters
#### Request Body
- **protoDefinition** (string) - Required - The content of the `.proto` file.
### Request Example
```csharp
var protoDefinition =
"""
option csharp_namespace = \"Test\";
syntax = \"proto3\";
import \"google/protobuf/empty.proto\";
package greet;
message HelloRequest { string name = 1; }
message HelloReply { string message = 1; }
message MyMessageEmpty { google.protobuf.Empty e = 1; }
""";
var converter = new Converter();
var request = new GetInformationRequest(protoDefinition);
GetInformationResponse response = await converter.GetInformationAsync(request);
```
### Response
#### Success Response (GetInformationResponse)
- **PackageNames** (string[]) - An array of package names found in the proto definition.
- **CSharpNamespaces** (string[]) - An array of C# namespaces generated from the proto definition.
- **MessageTypes** (Dictionary) - A dictionary mapping fully-qualified message type names to their compiled .NET `Type` objects.
```
--------------------------------
### ConvertAsync(ConvertToProtoBufRequest) with WithGrpcHeader()
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Uses the fluent `WithGrpcHeader()` method on `ConvertToProtoBufRequest` to prepend the gRPC framing prefix when serializing objects to ProtoBuf bytes.
```APIDOC
## ConvertAsync(ConvertToProtoBufRequest) with WithGrpcHeader()
### Description
Fluent method `.WithGrpcHeader()` on `ConvertToProtoBufRequest` enables adding the gRPC framing prefix when serializing objects to ProtoBuf bytes.
### Method
`IConverter.ConvertAsync` with `ConvertToProtoBufRequest.WithGrpcHeader()`
### Parameters
#### Request Body
- **protoDefinition** (string) - Required - The proto definition string.
- **messageType** (string) - Required - The fully-qualified name of the message type.
- **input** (object) - Required - The .NET object to serialize.
### Request Example
```csharp
var protoDefinition = ""; // Your proto definition
var converter = new Converter();
var obj = new { name = "stef" };
var request = new ConvertToProtoBufRequest(protoDefinition, "greet.HelloRequest", obj).WithGrpcHeader();
byte[] bytes = await converter.ConvertAsync(request);
```
### Response
#### Success Response (byte[])
- **bytes** (byte[]) - The resulting ProtoBuf bytes with the gRPC header prepended.
```
--------------------------------
### Add gRPC header to ProtoBuf bytes using WithGrpcHeader()
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Uses the fluent `.WithGrpcHeader()` method on `ConvertToProtoBufRequest` to prepend the gRPC framing prefix when serializing objects to ProtoBuf bytes.
```csharp
using ProtoBufJsonConverter;
using ProtoBufJsonConverter.Models;
var protoDefinition = /* the proto string shown above */;
var converter = new Converter();
var obj = new { name = "stef" };
var request = new ConvertToProtoBufRequest(protoDefinition, "greet.HelloRequest", obj)
.WithGrpcHeader(); // prepend 5-byte gRPC frame
byte[] bytes = await converter.ConvertAsync(request);
// Convert.ToBase64String(bytes) => "AAAAAAYKBHN0ZWY="
```
--------------------------------
### Inspect proto definition using GetInformationAsync
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Parses a `.proto` definition to retrieve package names, C# namespaces, and a mapping of message types to their compiled .NET `Type`. Useful for introspection and dynamic dispatch.
```csharp
using ProtoBufJsonConverter;
using ProtoBufJsonConverter.Models;
var protoDefinition =
"""
option csharp_namespace = "Test";
syntax = "proto3";
import "google/protobuf/empty.proto";
package greet;
message HelloRequest { string name = 1; }
message HelloReply { string message = 1; }
message MyMessageEmpty { google.protobuf.Empty e = 1; }
""";
var converter = new Converter();
var request = new GetInformationRequest(protoDefinition);
GetInformationResponse response = await converter.GetInformationAsync(request);
// response.PackageNames => ["google.protobuf", "greet"]
// response.CSharpNamespaces => ["Google.Protobuf.WellKnownTypes", "Test"]
// response.MessageTypes.Keys => ["Google.Protobuf.WellKnownTypes.Empty",
// "Test.HelloReply", "Test.HelloRequest",
// "Test.MyMessageEmpty"]
foreach (var (typeName, type) in response.MessageTypes)
{
Console.WriteLine($"{typeName} -> {type.FullName}");
}
```
--------------------------------
### Register and Inject MetadataReferenceService in Blazor WASM
Source: https://github.com/stefh/protobufjsonconverter/blob/main/src-webcil/Readme.md
Demonstrates how to register the BlazorWasmMetadataReferenceService with dependency injection and how to inject the IMetadataReferenceService interface.
```csharp
// Register
builder.Services.AddSingleton();
// Inject
IMetadataReferenceService service = ...;
```
--------------------------------
### Blazor WebAssembly Integration for ProtoBufJsonConverter
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Register BlazorWasmMetadataReferenceService and IConverter as singletons in Program.cs. Inject IConverter into Blazor pages to use it for converting protobuf to JSON.
```csharp
// Program.cs (Blazor WASM)
using MetadataReferenceService.BlazorWasm;
using ProtoBufJsonConverter;
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add("#app");
// Register the Blazor-specific metadata reference service and the converter
builder.Services.AddSingleton();
builder.Services.AddSingleton();
await builder.Build().RunAsync();
}
}
// Home.razor.cs (Blazor page)
public partial class Home
{
[Inject] public required IConverter Converter { get; set; }
private string _protoDefinition = /* your proto string */;
private string _messageType = "greet.HelloRequest";
private string _protobufBase64 = "CgRzdGVm";
private string _json = string.Empty;
private async Task ConvertAsync()
{
byte[] bytes = Convert.FromBase64String(_protobufBase64);
var request = new ConvertToJsonRequest(_protoDefinition, _messageType, bytes)
.WithSkipGrpcHeader(true)
.WithWriteIndented();
_json = await Converter.ConvertAsync(request);
// _json => { "name": "stef" }
}
}
```
--------------------------------
### Convert Object to ProtoBuf byte[] with gRPC Header
Source: https://github.com/stefh/protobufjsonconverter/blob/main/PackageReadme.md
Converts a C# object to a protobuf byte array and includes the gRPC header. Use the WithGrpcHeader() extension method for this.
```csharp
var protoDefinition = "...". // See above
var obj = new
{
name = "stef"
};
var request = new ConvertToProtoBufRequest(protoDefinition, "greet.HelloRequest", obj)
.WithGrpcHeader();
var converter = new Converter();
var protobufWithGrpcHeader = await ConvertAsync.Convert(request);
```
--------------------------------
### Convert Object to ProtoBuf byte[]
Source: https://github.com/stefh/protobufjsonconverter/blob/main/PackageReadme.md
Converts a C# object to a protobuf byte array using the proto definition. Ensure the object structure matches the specified message type.
```csharp
var protoDefinition = "...". // See above
var obj = new
{
name = "stef"
};
var request = new ConvertToProtoBufRequest(protoDefinition, "greet.HelloRequest", obj);
var converter = new Converter();
var protobuf = await converter.ConvertAsync(request);
```
--------------------------------
### ConvertAsync(ConvertToProtoBufRequest)
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Serializes a JSON string or a .NET object into ProtoBuf bytes. Optionally prepends the 5-byte gRPC framing header.
```APIDOC
## ConvertAsync(ConvertToProtoBufRequest)
### Description
Serializes a JSON string (or any .NET object) into a ProtoBuf `byte[]`. Optionally prepends the 5-byte gRPC framing header required by gRPC clients.
### Method
`IConverter.ConvertAsync`
### Parameters
#### Request Body
- **protoDefinition** (string) - Required - The proto definition string.
- **messageType** (string) - Required - The fully-qualified name of the message type.
- **input** (string | object) - Required - The JSON string or .NET object to serialize.
- **addGrpcHeader** (bool) - Optional - Whether to add the gRPC header (default is false).
### Request Example (JSON String)
```csharp
var protoDefinition = ""; // Your proto definition
var converter = new Converter();
string json = "{\"name\":\"stef\"}";
var requestFromJson = new ConvertToProtoBufRequest(protoDefinition, "greet.HelloRequest", json, addGrpcHeader: false);
byte[] bytes = await converter.ConvertAsync(requestFromJson);
```
### Request Example (Object)
```csharp
var protoDefinition = ""; // Your proto definition
var converter = new Converter();
var obj = new { name = "stef" };
var requestFromObj = new ConvertToProtoBufRequest(protoDefinition, "greet.HelloRequest", obj);
byte[] bytesFromObj = await converter.ConvertAsync(requestFromObj);
```
### Response
#### Success Response (byte[])
- **bytes** (byte[]) - The resulting ProtoBuf bytes.
```
--------------------------------
### Convert ProtoBuf byte[] to Object
Source: https://github.com/stefh/protobufjsonconverter/blob/main/PackageReadme.md
Converts a protobuf byte array to a C# object using the proto definition. Requires the proto definition and message type.
```csharp
var protoDefinition = "...". // See above
var bytes = Convert.FromBase64String("CgRzdGVm");
var request = new ConvertToObjectRequest(protoDefinition, "greet.HelloRequest", bytes);
var converter = new Converter();
var @object = await converter.ConvertAsync(request);
```
--------------------------------
### Convert ProtoBuf bytes to object using ConvertToObjectRequest
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Deserializes ProtoBuf bytes into a loosely-typed .NET object. Useful for reflection or further serialization. Requires the proto definition and message type.
```csharp
using ProtoBufJsonConverter;
using ProtoBufJsonConverter.Models;
var protoDefinition = /* the proto string shown above */;
var converter = new Converter();
byte[] bytes = Convert.FromBase64String("CgRzdGVm");
var request = new ConvertToObjectRequest(
protoDefinition,
messageType: "greet.HelloRequest",
protoBufBytes: bytes,
skipGrpcHeader: true // default
);
object result = await converter.ConvertAsync(request);
// result is a dynamically compiled instance; access via reflection or JSON serialize it
// Newtonsoft.Json.JsonConvert.SerializeObject(result) => {"name":"stef"}
```
--------------------------------
### Convert JSON string to ProtoBuf bytes using ConvertToProtoBufRequest
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Serializes a JSON string into ProtoBuf bytes. Optionally prepends the gRPC framing header. Can also serialize anonymous objects.
```csharp
using ProtoBufJsonConverter;
using ProtoBufJsonConverter.Models;
var protoDefinition = /* the proto string shown above */;
var converter = new Converter();
// From JSON string
string json = """{"name":"stef"}""";
var requestFromJson = new ConvertToProtoBufRequest(
protoDefinition,
messageType: "greet.HelloRequest",
input: json,
addGrpcHeader: false // default; set true to prepend gRPC frame
);
byte[] bytes = await converter.ConvertAsync(requestFromJson);
// Convert.ToBase64String(bytes) => "CgRzdGVm"
```
```csharp
// With gRPC header
var requestWithHeader = new ConvertToProtoBufRequest(protoDefinition, "greet.HelloRequest", json, addGrpcHeader: true);
byte[] grpcBytes = await converter.ConvertAsync(requestWithHeader);
// Convert.ToBase64String(grpcBytes) => "AAAAAAYKBHN0ZWY="
```
```csharp
// From anonymous object
var obj = new { name = "stef" };
var requestFromObj = new ConvertToProtoBufRequest(protoDefinition, "greet.HelloRequest", obj);
byte[] bytesFromObj = await converter.ConvertAsync(requestFromObj);
// Convert.ToBase64String(bytesFromObj) => "CgRzdGVm"
```
--------------------------------
### Convert JSON string to ProtoBuf byte[]
Source: https://github.com/stefh/protobufjsonconverter/blob/main/PackageReadme.md
Converts a JSON string to a protobuf byte array using the proto definition. Specify the proto definition and the target message type.
```csharp
var protoDefinition = "...". // See above
var json = @"{ "name":"stef" }";
var request = new ConvertToProtoBufRequest(protoDefinition, "greet.HelloRequest", json);
var converter = new Converter();
var protobuf = await converter.ConvertAsync(request);
```
--------------------------------
### ConvertAsync(ConvertToObjectRequest)
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Deserializes ProtoBuf bytes directly to a loosely-typed .NET object. This is useful when you need to reflect over the result or pass it to a serializer.
```APIDOC
## ConvertAsync(ConvertToObjectRequest)
### Description
Deserializes a ProtoBuf `byte[]` directly to a loosely-typed .NET `object` (a dynamically compiled type whose properties match the proto message fields), useful when you need to reflect over the result or pass it to a serializer.
### Method
`IConverter.ConvertAsync`
### Parameters
#### Request Body
- **protoDefinition** (string) - Required - The proto definition string.
- **messageType** (string) - Required - The fully-qualified name of the message type.
- **protoBufBytes** (byte[]) - Required - The ProtoBuf bytes to deserialize.
- **skipGrpcHeader** (bool) - Optional - Whether to skip the gRPC header (default is false).
### Request Example
```csharp
var protoDefinition = ""; // Your proto definition
var converter = new Converter();
byte[] bytes = Convert.FromBase64String("CgRzdGVm");
var request = new ConvertToObjectRequest(protoDefinition, "greet.HelloRequest", bytes, skipGrpcHeader: true);
object result = await converter.ConvertAsync(request);
```
### Response
#### Success Response (object)
- **result** (object) - A dynamically compiled .NET object representing the deserialized ProtoBuf data.
```
--------------------------------
### Convert ProtoBuf Bytes to JSON String
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Deserialize raw ProtoBuf `byte[]` into a JSON string. Provide the proto definition, message type, and optionally skip the gRPC header or enable indented JSON output. Handles both raw bytes and bytes with a gRPC framing header.
```csharp
using ProtoBufJsonConverter;
using ProtoBufJsonConverter.Models;
var protoDefinition = /* the proto string shown above */;
var converter = new Converter();
// "CgRzdGVm" is base64 for a HelloRequest{name:"stef"} without gRPC header
byte[] bytes = Convert.FromBase64String("CgRzdGVm");
var request = new ConvertToJsonRequest(
protoDefinition,
messageType: "greet.HelloRequest",
protoBufBytes: bytes,
skipGrpcHeader: true // default; set false if bytes carry a gRPC frame
)
.WithWriteIndented(); // optional: pretty-print JSON
string json = await converter.ConvertAsync(request);
// json => {"name":"stef"} (or indented form)
// With gRPC header bytes ("AAAAAAYKBHN0ZWY=" carries the 5-byte gRPC prefix)
byte[] grpcBytes = Convert.FromBase64String("AAAAAAYKBHN0ZWY=");
var grpcRequest = new ConvertToJsonRequest(protoDefinition, "greet.HelloRequest", grpcBytes, skipGrpcHeader: true);
string json2 = await converter.ConvertAsync(grpcRequest);
// json2 => {"name":"stef"}
```
--------------------------------
### Convert ProtoBuf byte[] to JSON string
Source: https://github.com/stefh/protobufjsonconverter/blob/main/PackageReadme.md
Converts a protobuf byte array to a JSON string using the proto definition. Ensure the proto definition and message type are correctly specified.
```csharp
var protoDefinition = "...". // See above
var bytes = Convert.FromBase64String("CgRzdGVm");
var request = new ConvertToJsonRequest(protoDefinition, "greet.HelloRequest", bytes);
var converter = new Converter();
var json = await converter.ConvertAsync(request);
```
--------------------------------
### Convert Protobuf to JSON in Blazor
Source: https://github.com/stefh/protobufjsonconverter/blob/main/README.md
Use this snippet within a Blazor component to convert Protobuf messages to JSON. Ensure the Converter service is injected and provide the Protobuf definition, message type, and base64 encoded Protobuf message.
```csharp
public partial class Home
{
[Inject]
public required IConverter Converter { get; set; }
private State _state = State.None;
private string _protoDefinition = "..."; // See above
private string _messageType = "greet.HelloRequest";
private string _protobufAsBase64 = "CgRzdGVm";
private bool _skipGrpcHeader = true;
private bool _addGrpcHeader = true;
private string _json = string.Empty;
private async Task OnClick()
{
await ConvertToJsonAsync();
}
private async Task ConvertToJsonAsync()
{
_json = string.Empty;
var bytes = Convert.FromBase64String(_protobufAsBase64);
var convertToJsonRequest = new ConvertToJsonRequest(_protoDefinition, _messageType, bytes)
.WithSkipGrpcHeader(_skipGrpcHeader)
.WithWriteIndented();
_json = await Converter.ConvertAsync(convertToJsonRequest);
}
}
```
--------------------------------
### ConvertAsync - ProtoBuf bytes to JSON string
Source: https://context7.com/stefh/protobufjsonconverter/llms.txt
Deserializes raw ProtoBuf byte arrays into JSON strings. Supports skipping gRPC framing headers and outputting indented JSON. Handles various Protobuf features like well-known types, oneof fields, and enums.
```APIDOC
## `IConverter.ConvertAsync(ConvertToJsonRequest)` — ProtoBuf bytes → JSON string
Deserializes a raw ProtoBuf `byte[]` into a JSON string using the supplied `.proto` definition and fully-qualified message type. Optionally skips the 5-byte gRPC framing header and outputs indented JSON.
```csharp
using ProtoBufJsonConverter;
using ProtoBufJsonConverter.Models;
var protoDefinition = ""; // the proto string shown above
var converter = new Converter();
// "CgRzdGVm" is base64 for a HelloRequest{name:"stef"} without gRPC header
byte[] bytes = Convert.FromBase64String("CgRzdGVm");
var request = new ConvertToJsonRequest(
protoDefinition,
messageType: "greet.HelloRequest",
protoBufBytes: bytes,
skipGrpcHeader: true // default; set false if bytes carry a gRPC frame
)
.WithWriteIndented(); // optional: pretty-print JSON
string json = await converter.ConvertAsync(request);
// json => {"name":"stef"} (or indented form)
// With gRPC header bytes ("AAAAAAYKBHN0ZWY=" carries the 5-byte gRPC prefix)
byte[] grpcBytes = Convert.FromBase64String("AAAAAAYKBHN0ZWY=");
var grpcRequest = new ConvertToJsonRequest(protoDefinition, "greet.HelloRequest", grpcBytes, skipGrpcHeader: true);
string json2 = await converter.ConvertAsync(grpcRequest);
// json2 => {"name":"stef"}
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.