JSON-RPC 2.0

Tips and tricks

Bits of wisdom related to the JSON-RPC protocol, its use, and the software offered here.

1. Why JSON-RPC 2.0?

Why choose version 2.0 of the JSON-RPC protocol over the original 1.0?

Because JSON-RPC 2.0 has:

2. Choose named parameters whenever you can

What do you gain from using named instead of positional parameters in your JSON-RPC 2.0 APIs?

3. Looking for a simple and high-performance Java JSON library?

If you you're looking for a JSON library for your Java project that is simple to use and offers blazing serialisation and parsing performance then JSON Smart is your thing. We rely on it for the JSON-RPC 2.0 Base & Co. and many other projects too.

JSON Smart has a JSON ↔ Java entity mapping that is intuitive and very easy to work with.

JSON Java
true|false java.lang.Boolean
number java.lang.Number
string java.lang.String
array java.util.List
object java.util.Map
null null

4. Composing JSON-RPC 2.0 requests in JavaScript

This is easy. After all, JSON has its origin in JavaScript.

Composing a positonal params request:

var request = {};
request.method = "ldap.search";
request.params = [];
request.params[0] = "45d0677d-a336-463b-ad99-c82137d03a00";
request.params[1] = "ou=people,dc=example,dc=com";
request.params[2] = "ONE";
request.params[3] = "(givenName=John)";
request.id = 1;
request.jsonrpc = "2.0";

Composing a named params request:

var request = {};
request.method = "ldap.search";
request.params = {};
request.params.CID = "45d0677d-a336-463b-ad99-c82137d03a00"
request.params.baseDN = "ou=people,dc=example,dc=com";
request.params.scope = "ONE";
request.params.filter = "(givenName=John)";
request.id = 1;
request.jsonrpc = "2.0";

5. Sending JSON-RPC 2.0 requests with jQuery

Use the jQuery.post() method:

var url = "http://rpc-service.net/jsonrpc2/";

var request = {};
request.method = "ldap.search";
request.params = {};
request.params.CID = "45d0677d-a336-463b-ad99-c82137d03a00";
request.params.baseDN = "ou=people,dc=example,dc=com";
request.params.scope = "ONE";
request.params.filter = "(givenName=John)";
request.id = 1;
request.jsonrpc = "2.0";

function displaySearchResult(response) {

        if (response.result)
                alert(response.result);

        else if (response.error)
                alert("Search error: " + response.error.message);
};

$.post(url, JSON.stringify(request), displaySearchResult, "json");

The above example assumes that you have jQuery 1.4+ and the json2 utility installed.