从Java中的URL获取JSON项
我有这个链接: 这存储在在线服务器上。很好,但我想得到一个像“hood\u id”或“damage\u或\u dent\u car\u id”这样的项目,但不知何故,当我启动它时,我的代码崩溃了。出现错误,未找到Json对象 这就是我所尝试的:从Java中的URL获取JSON项,java,json,Java,Json,我有这个链接: 这存储在在线服务器上。很好,但我想得到一个像“hood\u id”或“damage\u或\u dent\u car\u id”这样的项目,但不知何故,当我启动它时,我的代码崩溃了。出现错误,未找到Json对象 这就是我所尝试的: public class JSONParser { private String read(BufferedReader bufferedReader) throws IOException { //Creates new Str
public class JSONParser {
private String read(BufferedReader bufferedReader) throws IOException {
//Creates new StringBuilder to avoid escaping chars
StringBuilder stringBuilder = new StringBuilder();
//Gets the currentLine
String currentLine;
while((currentLine = bufferedReader.readLine()) !=null ){
//Adds the currentLine to the stringBuild if the currentLine is not null
stringBuilder.append(currentLine);
}
//Returns the StringBuilder is String format
return stringBuilder.toString();
}
public JSONObject readJsonFromUrl(String JSONurl) throws IOException, JSONException {
InputStream url = new URL(JSONurl).openStream();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url));
String jsonText = read(bufferedReader);
JSONArray jsonArray = new JSONArray("[" +jsonText + "]");
//JSONObject json = new JSONObject(jsonText);
JSONObject json = jsonArray.getJSONObject(0);
return json;
} finally {
url.close();
}
}
public void printJSON() throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://test.dontstealmywag.ga/api/damage_or_theft_car.php");
System.out.println(json.toString());
System.out.println(json.get("hood_id"));
}
}
当我输入json.get(“损坏”或“偷车”)代码>代码工作。有人能帮我吗?我认为问题出在JSONArray中,而JSONObject“hood_id”不在json的顶级层次结构中,这就是为什么您可能会得到:
org.json.JSONException:JSONObject[“hood_id”]未找到
行:System.out.println(json.get(“hood_id”)代码>
请确定:当您跑步时:
System.out.println(json.get("damage_or_theft_car"));
程序将执行该行并打印json内容
如果您确实想打印hood\u id
的值,则需要深入研究列表中的每个json。例如:
System.out.println(json.getJSONArray("damage_or_theft_car")
.getJSONObject(0).get("hood_id"));
“不知何故我的代码崩溃了”你说的不知何故是什么意思?你有错误吗?如果是,你能添加stacktrace吗?@Nathan抱歉添加了错误。找不到JsonObject请在此处发布完整的错误堆栈好吗?从IDE/浏览器复制并粘贴完整的堆栈跟踪。@Sanderbakker在哪一行?只需在你的问题中张贴stacktrace,它会更清晰^^^谢谢,这很有效。如何获取阵列的大小?不客气。要获得大小,只需使用length
:json.getJSONArray(“损坏”或“盗窃”汽车”).length()