【问题标题】:Processing error message 'The function getJSONArray(JSONArray) does not exist'处理错误消息“函数 getJSONArray(JSONArray) 不存在”
【发布时间】:2015-02-02 23:10:26
【问题描述】:

当我运行这个使用 json 查询到 Weather Underground 的草图时,我不确定为什么会收到错误消息 'The function getJSONArray(JSONArray) doesn't exist'。该评论似乎不合逻辑,因为 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);

}

【问题讨论】:

    标签: arrays json httpclient processing


    【解决方案1】:

    没有名为 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() 函数内。您可能希望在 responseReceived() 函数中从 hourly_forecast 中删除 JSONArray

    【讨论】:

    • 由于我正在加载的文件是一个包含各种 JSONArray 对象的 JSONObject,您如何建议我“抓取” JSONArray 项?
    猜你喜欢
    • 2012-09-30
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多