JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人读写,也易于机器解析和生成。而 Android 2.3 提供了解析 JSON 数据的库 —— org.json。
使用 org.json 库解析 JSON 数据主要有三个步骤:
1. 从网络获取 JSON 数据,可以使用 HttpURLConnection 或 OkHttp 等库。
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); InputStream inputStream = connection.getInputStream();
2. 将获取到的数据转换成 JSON 对象。
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } String json = stringBuilder.toString(); JSONObject jsonObject = new JSONObject(json);
3. 解析 JSON 对象,获取需要的数据。例如:
String name = jsonObject.getString("name"); int age = jsonObject.getInt("age"); JSONArray hobbies = jsonObject.getJSONArray("hobbies"); for (int i = 0; iorg.json 库还提供了其他方法来解析 JSON 数据,如 JSONArray、JSONTokener 等。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。