An open API service indexing awesome lists of open source software.

https://github.com/stefh/protobufjsonconverter

Convert a protobuf message to a JSON string or object using the proto definition file.
https://github.com/stefh/protobufjsonconverter

Last synced: 6 months ago
JSON representation

Convert a protobuf message to a JSON string or object using the proto definition file.

Awesome Lists containing this project

README

          

# ![Icon](./resources/icon-32x32.png) ProtoBufJsonConverter

## This project uses [protobuf-net](https://github.com/protobuf-net/protobuf-net) to:
- Convert a protobuf message to a JSON string using the proto definition file.
- Convert a protobuf message to an object using the proto definition file.
- Convert a JSON string or an object to a protobuf message using the proto definition file.
- Get information about the package names, message types and C# namespaces in the proto definition file.

## NuGet
[![NuGet Badge](https://img.shields.io/nuget/v/ProtoBufJsonConverter)](https://www.nuget.org/packages/ProtoBufJsonConverter)

## Usage

### Proto Definition
``` 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;
}
```

### :one: Convert ProtoBuf `byte[]` to a JSON `string`

``` mermaid
---
title: "Convert ProtoBuf byte[] to a JSON string"
---
flowchart LR
Def["ProtoBuf Definition\n(.proto)"] --> protobuf_net["protobuf-net:\n\nGenerate C# code"]
Bytes["ProtoBuf bytes"] --> Des["protobuf-net:\n\nDeserialize ProtoBuf bytes to instance\n(using the MessageType\nand the object-type)"]
MessageType["Message Type"] --> Des
protobuf_net --> CodeCompile["Compile C# code\nto Assembly"]
CodeCompile --> CodeType["typeof(object)"]
CodeType --> Des
Des --> JSON2OBJ["Serialize instance\nto JSON"]
```

#### Code
``` 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);
```

#### JSON
``` json
{"name":"stef"}
```

### :two: Convert ProtoBuf `byte[]` to an object

#### Code
``` 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);
```

### :three: Convert JSON `string` to a ProtoBuf `byte[]`
#### Code
``` 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);
```

### :four: Convert any `object` to a ProtoBuf `byte[]`

``` mermaid
---
title: "Convert an object to a ProtoBuf byte[]"
---
flowchart LR
Def["ProtoBuf Definition\n(.proto)"] --> protobuf_net["protobuf-net:\n\nGenerate C# code"]
protobuf_net --> CodeCompile["Compile C# code\nto Assembly"]
CodeCompile --> CodeType["typeof(object)"]
CodeType --> Ser
Object["Object"] --> OBJ2JSON["Serialize object\nto JSON"]
OBJ2JSON --> JSON2INS["Deserialize JSON to instance\n(using the object-type)"]
JSON2INS --> Ser["protobuf-net:\n\nSerialize instance to ProtoBuf bytes\n(using the MessageType)"]
MessageType["Message Type"] --> Ser
```

#### Code
``` 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);
```

### :five: Convert any `object` to a ProtoBuf `byte[]` including the Grpc Header
#### Code
``` 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);
```

---

## Using in Blazor WebAssembly
In order to use this library in a Blazor WebAssembly application, you need to provide a specific Blazor implementation for the `IMetadataReferenceService`, the [BlazorWasmMetadataReferenceService](https://github.com/StefH/ProtoBufJsonConverter/blob/main/examples/ProtoBufJsonConverter.Blazor/BlazorWasmMetadataReferenceService.cs).

### Convert ProtoBuf `byte[]` to a JSON `string`

#### Dependency Injection
``` 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();
}
}
```

#### Blazor Page
``` 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);
}
}
```

For a full example, see [examples/ProtoBufJsonConverter.Blazor](https://github.com/StefH/ProtoBufJsonConverter/tree/main/examples/ProtoBufJsonConverter.Blazor).

### :six: Get information about the package names, message types and C# namespaces
#### Code
``` 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;
```

---

## :computer: Examples
- [Blazor WASM](https://protobuf.heyenrath.nl)
- [Blazor Static Web App](https://zealous-desert-029b2f003.4.azurestaticapps.net/)

## :books: Resources
- [protogen](https://protogen.marcgravell.com)
- [protobufpal](https://www.protobufpal.com)
- [protobuf-decoder](https://protobuf-decoder.netlify.app)

-
## Sponsors

[Entity Framework Extensions](https://entityframework-extensions.net/?utm_source=StefH) and [Dapper Plus](https://dapper-plus.net/?utm_source=StefH) are major sponsors and proud to contribute to the development of **ProtoBufJsonConverter**.

[![Entity Framework Extensions](https://raw.githubusercontent.com/StefH/resources/main/sponsor/entity-framework-extensions-sponsor.png)](https://entityframework-extensions.net/bulk-insert?utm_source=StefH)

[![Dapper Plus](https://raw.githubusercontent.com/StefH/resources/main/sponsor/dapper-plus-sponsor.png)](https://dapper-plus.net/bulk-insert?utm_source=StefH)