处理错误消息'函数getJSONArray(JSONArray)不存在'

时间:2015-02-02 23:10:26

标签: arrays json httpclient processing

当我运行使用json查询到Weather Underground的草图时,我不知道为什么我收到错误消息'函数getJSONArray(JSONArray)不存在'。这个评论似乎不合逻辑,因为Processing正在识别JSONArray的id ref。

.json可以在这里阅读:http://api.wunderground.com/api/97a2805510de59e9/hourly/q/pws:IENGLAND274.json

有什么想法?感谢。

import com.francisli.processing.http.*;

HttpClient client;
String data;
com.francisli.processing.http.JSONObject weatherInfo;

JSONArray hourly_forecast;

int last = 0;
PImage img;
Float humidity = 50.2;



void setup() {
  size(700, 700);

  client = new HttpClient(this, "api.wunderground.com");

  client.GET("/api/97a2805510de59e9/hourly/q/pws:IENGLAND274.json");

  background(255);
}

void responseReceived(HttpRequest request, HttpResponse response) {

  println(response.getContentAsString());

  weatherInfo = response.getContentAsJSONObject();

  JSONArray hourly_forecast = weatherInfo.getJSONArray(hourly_forecast);

}

1 个答案:

答案 0 :(得分:0)

没有名为getJSONArray()的方法将JSONArray作为参数。

该函数应该用作JSONArray.getJSONArray(0),它获取JSON数据中的第一个元素数组。你可以将它放在循环中以获得所有这些。

示例(摘自:http://art.buffalo.edu/coursenotes/art380/reference/JSONArray_getJSONArray_.html):

// The following short JSON file called "data.json" is parsed 
// in the code below. It must be in the project's "data" folder.
//
// [
//   [
//     { "name": "apple", "isFruit": true },
//     { "name": "grape", "isFruit": true },
//     { "name": "carrot", "isFruit": false }
//   ],
//   [
//     { "name": "lettuce", "isFruit": false },
//     { "name": "plum", "isFruit": true },
//     { "name": "cinnamon", "isFruit": false }
//   ]
// ]

JSONArray json;

void setup() {

  json = loadJSONArray("data.json");

  // Get the first array of elements
  JSONArray values = json.getJSONArray(0);

  for (int i = 0; i < values.size(); i++) {

    JSONObject item = values.getJSONObject(i); 

    String name = item.getString("name");
    boolean isFruit = item.getBoolean("isFruit");

    println(name + ", " + isFruit);
  }
}

// Sketch prints:
// apple, true
// grape, true
// carrot, false

您的代码存在的第二个问题是,您需要两次声明hourly_forecast:一次全局,一次在responseReceived()函数内。您可能希望从JSONArray函数中的hourly_forecast中删除responseReceived()