如何将JSON文件内容存入数组并通过URL访问JSON(Java Gson实现)
实现方案
1. 本地JSON文件内容转数组
你现有代码混合使用了Gson和org.json的JSONArray,建议统一逻辑处理,步骤如下:
- 先补全
loadJSONFromAsset方法,该方法用于读取Android assets目录下的JSON文件并转为字符串:
private String loadJSONFromAsset(Context context, String fileName) { String json = null; try { InputStream is = context.getAssets().open(fileName); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, StandardCharsets.UTF_8); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; }
- 如果你需要将JSON转为自定义对象数组,用Gson直接解析更方便,假设JSON数组内元素对应
YourBean类:
Gson gson = new GsonBuilder().create(); String jsonStr = loadJSONFromAsset(context, "你的JSON文件名.json"); // 转自定义对象数组 YourBean[] beanArray = gson.fromJson(jsonStr, YourBean[].class); // 也可以直接转List List<YourBean> beanList = Arrays.asList(beanArray);
- 如果你坚持使用
JSONArray,直接解析返回的字符串即可:
String jsonStr = loadJSONFromAsset(context, "你的JSON文件名.json"); JSONArray array = new JSONArray(jsonStr);
2. 通过URL访问远程JSON资源
注意网络请求不能放在主线程执行,以下是原生HttpURLConnection结合Gson实现的示例:
new Thread(() -> { String jsonResult = null; HttpURLConnection connection = null; try { URL url = new URL("你的远程JSON资源URL"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } jsonResult = response.toString(); // 解析为数组,逻辑和本地解析一致 Gson gson = new GsonBuilder().create(); YourBean[] remoteBeanArray = gson.fromJson(jsonResult, YourBean[].class); // 后续数组处理逻辑,若要更新UI需切回主线程执行 } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } }).start();
注意事项
- 如果是Android环境,需要在清单文件中添加网络权限:
<uses-permission android:name="android.permission.INTERNET" /> - 生产环境建议使用OkHttp、Retrofit等成熟网络库处理请求,无需自行实现原生请求逻辑
- 解析前需要对JSON字符串判空,避免空指针异常
内容的提问来源于stack exchange,提问作者user200821
相关产品推荐
相关产品推荐

