GRPC.Codec.JSON (gRPC Core v1.0.0)

Copy Markdown View Source

JSON Codec for gRPC communication.

This module implements the GRPC.Codec behaviour, providing encoding and decoding functions for JSON serialization in the context of gRPC communication.

Configuration

By default, the codec uses emit_unpopulated: true to include all fields with default values. You can override this behavior by:

  1. Passing options to encode/2:

    GRPC.Codec.JSON.encode(struct, emit_unpopulated: false)
  2. Setting application config:

    config :grpc, GRPC.Codec.JSON, emit_unpopulated: false

This module requires the Jason dependency.

Summary

Functions

Decodes binary data into a map using the Jason library. Parameters

Encodes a struct using the Protobuf.JSON.encode!/2 function.

Callback implementation for GRPC.Codec.name/0.

Functions

decode(binary, module)

Decodes binary data into a map using the Jason library. Parameters:

binary - The binary data to be decoded.
module - Module to be created.

Returns:

A map representing the decoded data.

Raises:

Raises an error if the Jason library is not loaded.

Example:

binary_data |> GRPC.Codec.JSON.decode(__MODULE__)

encode(struct, opts \\ [])

Encodes a struct using the Protobuf.JSON.encode!/2 function.

By default, uses emit_unpopulated: true unless configured otherwise via application config or explicitly passed in opts.

Parameters:

  • struct - The struct to be encoded.
  • opts - Keyword list of options to pass to Protobuf.JSON.encode!/2. Defaults to [].

Returns:

The encoded binary data.

Examples:

# Using default options (from config or emit_unpopulated: true)
%MyStruct{id: 1, name: "John"} |> GRPC.Codec.JSON.encode()

# Overriding with custom options
 GRPC.Codec.JSON.encode(%MyStruct{id: 1, name: "John"}, emit_unpopulated: false)

name()

Callback implementation for GRPC.Codec.name/0.