0

我正在使用Unirest 库来解析我从 MAshape API 获得的一些 JSON。我是使用 Java 发出 HTTP 请求的新手,我无法理解错误。

我做的功能是:

public ArrayList<String> httpPost(int year) {
    HttpResponse<String> response = null;
    try {
        response = Unirest.post("https://--------.p.mashape.com/v1/calculate/" + year)
                .header("X-Mashape-Key", "--------------------------")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("Accept", "application/json")
                //.field("blabla", "blabla")
                .field("filing_status", myFS)
                .field("pay_periods", myPP)
                .field("pay_rate", getGrossPay())
                .field("state", myState)
                .asString();
    } catch (UnirestException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // retrieve the parsed JSONObject from the response
    JSONObject myObj = new JSONObject(response);
    JSONArray results = new JSONArray();
    try {
        results = myObj.getJSONArray("annual"));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    ArrayList<String> list = new ArrayList<String>(); 
    if (results != null) { 
       int len = results.length();
       for (int i=0;i<len;i++){ 
        try {
            list.add(results.get(i).toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       } 
    }
    return list;
}

我得到错误:

org.json.JSONException: JSONObject["annual"] not found

所以我将response变量输出到一个文件中,该文件有com.mashape.unirest.http.HttpResponse@161b062a在其中。我不知道那是从哪里来的。

只是为了检查一下,我使用了 hurl.it并且我对程序的相同响应产生了成功的响应:

{
  "annual": {
    "state": {
      "amount": 68232.65
    },
    "fica": {
      "amount": 91800
    },
    "federal": {
      "amount": 418014.8
    }
  },
  "per_pay_period": {
    "state": {
      "amount": 5686.05
     },
     "fica": {
      "amount": 7650
    },
    "federal": {
      "amount": 34834.57
    }
  }
}

我尝试将 from 的类型更改为responseto StringJsonNode但它没有用,而且我真的不知道如何使用它。我还添加了所有必需的库。有什么帮助吗?

4

1 回答 1

0

利用myObj.getJSONObject("annual");

于 2015-09-11T03:32:15.753 回答