我尝试用书制作应用程序,在我看来,我在本书中发现了错误 我们可以在这本书中读到:
这一行读取"天气"表,访问的第一个元素 包含天气状况描述的数组 一天,并说明图标
他们给出了这一行:
JSONObject weather =
day.getJSONArray("weather").getJSONObject(0);
来自这个班级
private void convertJSONtoArrayList(JSONObject forecast) {
weatherList.clear();
try {
JSONArray list = forecast.getJSONArray("list");
for (int i = 0; i < list.length(); ++i) {
JSONObject day = list.getJSONObject(i);
JSONObject temperatures = day.getJSONObject("temp");
JSONObject weather =
day.getJSONArray("weather").getJSONObject(0);
weatherList.add(new Weather(
day.getLong("dt"),
temperatures.getDouble("min"),
temperatures.getDouble("max"),
day.getDouble("humidity"),
weather.getString("description"),
weather.getString("icon")));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
这是我认为的错误(他们强调3和4元素,而不是第1个元素):
1 {
2 "city": {
3 "id": 5128581,
4 "name": "New York",
5 "coord": {
6 "lon": -74.005966,
7 "lat": 40.714272
8 },
9 "country": "US",
10 "population": 0
11 },
12 "cod": "200",
13 "message": 0.0102,
14 "cnt": 2,
15 "list": [{
16 "dt": 1442419200,
17 "temp": {
18 "day": 79.9,
19 "min": 71.74,
20 "max": 82.53,
21 "night": 71.85,
22 "eve": 82.53,
23 "morn": 71.74
24 },
25 "pressure": 1037.39,
26 "humidity": 64,
27 "weather": [{
28 "id": 800,
29 "main": "Clear",
30 "description": "sky is clear", <-- they underline this
31 "icon": "old" <-- and this
32 }],
33 "speed": 0.92,
34 "deg": 250,
35 "clouds": 0
36 }, {
37 "dt": 1442505600,
38 "temp": {
39 "day": 79.92,
40 "min": 66.72,
41 "max": 83.1,
42 "night": 70.79,
43 "eve":81.99,
44 "morn": 66.72
45 },
46 "pressure": 1032.46,
47 "humidity": 62,
48 "weather": [{
49 "id": 800,
50 "main": "Clear",
51 "description": "sky is clear",
52 "icon": "01d"
53 }],
54 "speed": 1.99,
55 "deg": 224,
56 "clouds": 0
57
答案 0 :(得分:2)
书中没有错误。它只是JSON解析。
JSONObject weather =
day.getJSONArray("weather").getJSONObject(0);
上面的live会给你一个JSONObject
{
28 "id": 800,
29 "main": "Clear",
30 "description": "sky is clear", <-- they underline this
31 "icon": "old" <-- and this
32 }
答案 1 :(得分:1)
这本书是对的。
请注意,数组中的第一项既不是描述也不是图标。相反,它是一个完整的json对象:
{
"id": 800,
"main": "Clear",
"description": "sky is clear",
"icon": "old"
}
一旦他们使用getJSONObject(0)
获取此对象,他们就会访问其描述和图标条目(顺便说一句,这是无序的,因为对象中的json条目是无序的)。
答案 2 :(得分:1)
书籍示例是正确的,可以解释如下。 在上面的代码片段中,它为每个数组元素读取以下值: