Java - 嵌套 JSON 个对象

Java - Nested JSON objects

我正在尝试为 XBMC/KODI 创建一个简单的 JAVA 遥控器,我认为到目前为止我做得还不错(仍处于早期阶段)但是当我到达嵌套 JSON对象。

这是我要转换成的原始代码 JAVA:

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

到目前为止,我已经在 JAVA 中完成了此操作:

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());
    }}

正如您从原始 JSON 中看到的那样,{} 中有一个嵌套的 {},所以 {{}} 我不知道如何处理它。如果有帮助,我将在 eclipse 中使用 JSON-Simple,感谢您的帮助!

编辑:

这很有帮助,谢谢,但它实际上不起作用语法有什么问题:

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());
    }
}

为参数创建另一个 JSONObject,设置它,然后使用键 params.

将其添加到父 JSONObject

//导入java.util.ArrayList;

//导入org.bson.Document;

Document root= new Document();

Document rootParams = new Document();


root.append("jsonrpc","2.0");

root.append("method","Player.PlayPause");

rootParams.append("playerid",0);

root.append("id",1);




if (!rootParams.isEmpty()){
root.append("params",rootParams);
}


System.out.println(root.toJson());