需要将下面的JSON对象转换为String JAVA,卡住了如何处理嵌套数组。以下是JSON对象:

{
  "url": "https://www.apple.com",
  "defer_time": 5,
  "email": true,
  "mac_res": "1024x768",
  "win_res": "1366X768",
  "smart_scroll": true,
  "layout": "portrait",
  "configs": {
    "windows 10": {
      "chrome": [
        "76",
        "75"
      ],
      "firefox": [
        "67",
        "66"
      ]
    },
    "macos mojave": {
      "chrome": [
        "76",
        "75"
      ],
      "firefox": [
        "67",
        "66"
      ]
    }
  }
}


当前,我正在使用JSONObject和JSONArray编写代码,但无法使其正确用于嵌套数组。

任何帮助将不胜感激,非常感谢!

最佳答案

我希望这段代码可以为您清除所有内容。首先阅读json文件,您可以使用流打开它,它们直接将流传递给JSONObject,因为它具有执行此技巧的构造函数,或者将文件中的字符串附加到StringBuilder,然后将stringbuilder传递给字符串到JSONObject。

 public static void main(String[] args) {
    try(BufferedReader fileReader = new BufferedReader(new FileReader("test.json"))){
        String line="";
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = fileReader.readLine()) !=null){
            stringBuilder.append(line);
        }
        JSONObject jsonObject = new JSONObject(stringBuilder.toString());
        // to add single values yo your array.
        // you can do something like this
        JSONObject config = jsonObject.getJSONObject("configs");
        JSONObject macos_mojave = config.getJSONObject("macos mojave");
        JSONArray jsonArray  = macos_mojave.getJSONArray("chrome"); // this way you will reach the array
        jsonArray.put("77"); // then you can add them new values
        jsonArray.put("78");
        System.out.println(jsonArray.toList()); //will print your array content
    } catch (IOException e){
        e.printStackTrace();
    }

    JSONArray jsonArray = new JSONArray(); // this is what you call single values, it is array
    jsonArray.put(75);
    jsonArray.put(76);

    JSONObject jsonObject1 = new JSONObject();
    jsonObject1.put("Something", jsonArray);
}


您可以像这样将它们写回到文件中

//if you write them back to file you will see that 77 and 78 was added to chrome array (single values as you call them)
    try(FileWriter fileWriter = new FileWriter("test.json")){
        fileWriter.write(jsonObject.toString(5));
    }catch (IOException ignore){

    }


在打开test.json文件后,结果将是下一个

{
 "win_res": "1366X768",
 "layout": "portrait",
 "configs": {
      "windows 10": {
           "chrome": [
                "76",
                "75"
           ],
           "firefox": [
                "67",
                "66"
           ]
      },
      "macos mojave": {
           "chrome": [
                "76",
                "75",
                "77",
                "78"
           ],
           "firefox": [
                "67",
                "66"
           ]
      }
 },
 "smart_scroll": true,
 "defer_time": 5,
 "mac_res": "1024x768",
 "url": "https://www.apple.com",
 "email": true


}

如您所见77和78被附加到“ chrome” JSONArray。文件将不会跟踪顺序,因为它在后台使用HashMap。

07-25 23:33
查看更多