jsonsocketsxbmckodi

Java - Nested JSON objects


I am trying to create a simple JAVA remote for XBMC/KODI and I think im doing ok so far (still early days) but I have hit a snag when I reached a nested JSON object.

This is the original code I am converting to JAVA:

{"jsonrpc": "2.0", "method": "Player.PlayPause", "params": { "playerid": 0 }, "id": 1}

I have done this in JAVA so far:

public static void main(String[] args) throws UnknownHostException, IOException{
    JSONObject json = new JSONObject();
    json.put("jsonrpc", "2.0");
    json.put("method", "Player.PlayPause");
    //json.put("params", "playerid = 0"); THIS IS THE LINE I am having issues with
    Socket s = new Socket("192.168.0.21", 8080);
    try (OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8)) {
                out.write(json.toString());
    }}

As you can see from the original JSON there is a nested {} within the {} so {{}} and I dont know how to handle this. Im using JSON-Simple in eclipse if this helps, thanks for any help!

EDIT:

So that was helpful thanks, but it doesnt actually work is there anything wrong with the syntax:

public static void main(String[] args) throws UnknownHostException, IOException{
    JSONObject json = new JSONObject();
    JSONObject params = new JSONObject();
    json.put("jsonrpc", "2.0");
    json.put("method", "Player.PlayPause");
    params.put("playerid", 0);
    json.put("params", params);
    json.put("id", 1);
    Socket s = new Socket("192.168.0.21", 8080);
    try (OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8)) {
                out.write(json.toString());
    }
}

Solution

  • Create another JSONObject for the params, set it up, and add it to the parent JSONObject with the key params.