将要用到两个类:JSONArray、JSONObject
JSONArray:作用于json对象数组,例如
[{"key1","value1"},{"key2","value2"}]
JSONObject:作用于json对象,例如
{"key","value"}
具体用法:
后端是webapi的时候,通过get/post 请求得到json字符串,下面是我自己封装的Http方法,返回一个JSONArray:
private JSONArray Http(String url, HttpURLConnection conn, String Method) throws Exception {
JSONArray jsonArray = null;
//发送请求
URL urls = new URL(url);
conn = (HttpURLConnection) urls.openConnection();
conn.setRequestMethod(Method);
//判断请求结果,请求码200请求成功
if (conn.getResponseCode() == 200) {
//字节输入流
InputStream in = conn.getInputStream();
//字节输入流转String
Scanner scanner = new Scanner(in);
String json = "";
scanner.useDelimiter("");
while (scanner.hasNext()) {
json += scanner.next();
}
//String转JSONArray
jsonArray = new JSONArray(json);
}
return jsonArray;
}
通过请求得到josn字符串后转换成JSONArray json数组
如果请求返回的直接是json对象可以直接用new JSONObject(string)
得到JSONArray对象后,for循环遍历json数组得到json对象:
//jsonArray:通过请求取得的字符串转换的JSONArray对象
for(int i=0;i<jsonArray.length();i++){
JSONObject item=jsonArray.getJSONObject(i)
//得到值,key:对象的键
String text= item.getString("key");
//JSONObject有多种数据类型方法,很方便的将json对象的值转换成常用的变量
}
注 意 : 字 符 串 转 J S O N A r r a y / J S O N O b j e c t 要 抛 出 异 常 \color{red}{注意:字符串转JSONArray/JSONObject要抛出异常} 注意:字符串转JSONArray/JSONObject要抛出异常