try { JSONObject data=new JSONObject(s); String reason=data.getString("reason"); JSONArray results=data.getJSONArray("results"); JSONObject resultbean =results.getJSONObject(0); String city=resultbean.getString("city"); JSONObject ctime=results.getJSONObject(1); String ctrue=ctime.getString("temperature"); String chumidity=ctime.getString("humidity"); String cinfo=ctime.getString("info"); String cwid=ctime.getString("wid"); String cdirect=ctime.getString("direct"); String cpower=ctime.getString("power"); String caqi=ctime.getString("aqi"); tv.setText(reason+"\n"+city+"\n"+caqi+"\n"); } catch (JSONException e) { e.printStackTrace(); } }
时间: 2024-04-28 13:19:41 浏览: 11
您修改后的代码看起来应该没有问题了,使用getString()方法可以确保在JSON对象中不存在该属性时会抛出JSONException异常,避免了空指针异常的发生。
如果您仍然遇到应用程序闪退的问题,建议您使用Log打印输出来检查哪一行代码引发了异常,并提供相关的堆栈跟踪信息,以便进一步分析问题的原因。
相关问题
JSONObject jsonObject = new JSONObject(getJson);
根据提供的引用内容,无法确定`getJson`的具体含义,因此无法对`JSONObject jsonObject = new JSONObject(getJson)`进行详细介绍或演示。但是,可以根据引用内容提供一些关于`JSONObject`和`JSONArray`的基本知识和用法。
`JSONObject`和`JSONArray`是Java中处理JSON数据的两个主要类。`JSONObject`表示一个JSON对象,`JSONArray`表示一个JSON数组。可以使用这两个类来解析和构建JSON数据。
下面是一个简单的例子,演示如何使用`JSONObject`和`JSONArray`解析JSON数据:
```java
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\", \"pets\":[\"dog\", \"cat\"]}";
JSONObject jsonObject = new JSONObject(jsonString);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
String city = jsonObject.getString("city");
JSONArray pets = jsonObject.getJSONArray("pets");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
System.out.println("Pets: " + pets.toString());
}
}
```
在上面的例子中,我们首先定义了一个JSON字符串`jsonString`,然后使用`JSONObject`将其解析为一个JSON对象。接着,我们使用`getString`、`getInt`和`getJSONArray`等方法从JSON对象中获取数据。最后,我们将获取到的数据打印出来。
详细解释下面代码:import org.json.JSONObject; public class ParseJSON { ParseJSON(String jsonData){ JSONObject jsonObj = new JSONObject(jsonData); int code = jsonObj.getInt("code"); String message = jsonObj.getString("message"); JSONArray data = jsonObj.getJSONArray("data"); for(int i=0;i<data.length();i++){ JSONObject obj = data.getJSONObject(i); String name = obj.getString("name"); int age = obj.getInt("age"); System.out.println(name + "," + age); } } }
这段代码是一个解析 JSON 数据的 Java 类,主要实现了以下功能:
1. 导入 org.json.JSONObject 库,用于解析 JSON 数据。
2. 定义了一个名为 ParseJSON 的类,其中包含一个构造方法 ParseJSON(String jsonData),该方法接收一个 JSON 字符串作为参数。
3. 在构造方法中,先通过 JSONObject 的构造函数将传入的 jsonData 字符串解析为一个 JSONObject 对象。
4. 从 JSONObject 对象中获取 code、message 和 data 三个字段的值,其中 code 和 message 是基本数据类型,可以通过 getInt() 和 getString() 方法获取;而 data 是一个数组类型,需要通过 getJSONArray() 方法获取。
5. 遍历 data 数组中的每个元素,将每个元素解析为一个 JSONObject 对象,从中获取 name 和 age 两个字段的值,并将其输出到控制台中。
总体来说,这段代码实现了对 JSON 数据的解析,并将其中的数据提取和输出。需要注意的是,这里使用了第三方库 org.json.JSONObject,因此在使用前需要先将该库导入到项目中。