Here are some initial examples and projects where you can see how you can create your own ...
1. A way to create new JSON objects to send
import java.util.UUID; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; protected JSONObject toJSONRequest(String method, Object[] params) throws JSONRPCException { //Copy method arguments in a json array JSONArray jsonParams = new JSONArray(); for (int i=0; i<params.length; i++) { if(params[i].getClass().isArray()){ jsonParams.put(getJSONArray((Object[])params[i])); } jsonParams.put(params[i]); } //Create the json request object JSONObject jsonRequest = new JSONObject(); try { jsonRequest.put("id", UUID.randomUUID().hashCode()); jsonRequest.put("method", method); jsonRequest.put("params", jsonParams); } catch (JSONException e1) { throw new JSONRPCException("Invalid JSON request", e1); } return jsonRequest; }
Source adapted from: https://code.google.com/p/android-json-rpc/source/browse/trunk/android-json-rpc/src/org/alexd/jsonrpc/JSONRPCClient.java?r=47
Or using GSON:
Gson gson = new Gson(); JsonObject req = new JsonObject(); req.addProperty("id", id); req.addProperty("method", methodName); JsonArray params = new JsonArray(); if (args != null) { for (Object o : args) { params.add(gson.toJsonTree(o)); } } req.add("params", params); String requestData = req.toString();
From org / json / rpc / client / JsonRpcInvoker.java json-rpc-client
2. A way to connect to another program and send my answer
Using HTTP, you can do the following:
URL url = new URL("http://..."); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.connect(); OutputStream out = null; try { out = connection.getOutputStream(); out.write(requestData.getBytes()); out.flush(); out.close(); int statusCode = connection.getResponseCode(); if (statusCode != HttpURLConnection.HTTP_OK) { throw new JsonRpcClientException("unexpected status code returned : " + statusCode); } } finally { if (out != null) { out.close(); } }
Source adapted from org / json / rpc / client / HttpJsonRpcClientTransport.java json-rpc-client
3. Method for decoding JSON response
Read the HTTP response and then parse the JSON:
InputStream in = connection.getInputStream(); try { in = connection.getInputStream(); in = new BufferedInputStream(in); byte[] buff = new byte[1024]; int n; while ((n = in.read(buff)) > 0) { bos.write(buff, 0, n); } bos.flush(); bos.close(); } finally { if (in != null) { in.close(); } } JsonParser parser = new JsonParser(); JsonObject resp = (JsonObject) parser.parse(new StringReader(bos.toString())); JsonElement result = resp.get("result"); JsonElement error = resp.get("error");
Keep in mind that these fragments compose together with existing JSON RPC client libraries, so this is not verified and may not compile as is, but should give you a good basis for working.