mjsonrpc 1.0
A lightweight JSON-RPC 2.0 message parser and generator based on cJSON
Loading...
Searching...
No Matches
mjsonrpc - A JSON-RPC 2.0 Message Parser and Generator Based on cJSON

GitHub Actions Workflow Status GitHub License GitHub commit activity GitHub top language GitHub repo size GitHub Downloads (all assets, latest release)

[ English | 中文 ]

Introduction

This project is lightweight, has minimal dependencies, and can be integrated into various communication methods (TCP, UDP, message queues, etc.). It is simple to use (with only a few functional APIs) and has good performance (using hash-based indexing instead of polling all methods). It also supports batch calls (JSON Array), automatic generation of corresponding error messages or custom error messages based on requests, customizable memory management hooks, and notification requests.

How to Use

Simply add the project source files (mjsonrpc.c, mjsonrpc.h) and the cJSON library to your own project and compile them together. Alternatively, you can compile them into a dynamic library and link it.

Function Definitions

For detailed API descriptions, please refer to src/mjsonrpc.h and Doxygen docs of this repo.

Example

#include "mjsonrpc.h"
#include <stdio.h>
#include <stdlib.h>
// Define a simple JSON-RPC method
cJSON *hello_world(mjrpc_func_ctx_t *context, cJSON *params, cJSON *id) {
cJSON *result = cJSON_CreateString("Hello, World!");
return result;
}
int main() {
// Initialize mjrpc_handle_t
// Add a method
mjrpc_add_method(handle, hello_world, "hello", NULL);
// Construct a JSON-RPC request
const char *json_request = "{\"jsonrpc\":\"2.0\",\"method\":\"hello\",\"id\":1}";
// Process the request
int result;
char *json_response = mjrpc_process_str(handle, json_request, &result);
// Check return code
if (result != MJRPC_RET_OK) {
printf("Error processing request: %d\n", result);
}
// Check response string
if (json_response) {
printf("Response: %s\n", json_response);
free(json_response);
}
// Cleanup
return 0;
}
int mjrpc_destroy_handle(mjrpc_handle_t *handle)
Destroy a JSON-RPC handle and free all associated memory.
mjrpc_handle_t * mjrpc_create_handle(size_t initial_capacity)
Create a new JSON-RPC handle.
int mjrpc_add_method(mjrpc_handle_t *handle, mjrpc_func function_pointer, const char *method_name, void *arg2func)
Register a new RPC method.
char * mjrpc_process_str(mjrpc_handle_t *handle, const char *request_str, int *ret_code)
Process a JSON-RPC request string.
A lightweight JSON-RPC 2.0 message parser and generator based on cJSON.
@ MJRPC_RET_OK
Operation completed successfully.
Definition mjsonrpc.h:87
Context structure passed to RPC method callback functions.
Definition mjsonrpc.h:122
Main handle structure for managing RPC methods.
Definition mjsonrpc.h:175

References