gpt4 book ai didi

java - 需要将下面的 JSON 对象转换为 String JAVA

转载 作者:行者123 更新时间:2023-12-01 23:37:48 24 4
gpt4 key购买 nike

需要将下面的 JSON 对象转换为 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。

关于java - 需要将下面的 JSON 对象转换为 String JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58273269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com