Java JSON返回一个数组作为值

时间:2015-11-03 23:57:17

标签: java arrays json

我有一个像

这样的JSON对象
{
    "endtime": 1446188340,
    "interval": 60,
    "metrics": {
        "heartrate": {
            "values": [
                88,
                92,
                88,
                89,
                86,
                84,
                82,
                86,
                97,
                77,
                81,
                87,
                83,
                101,
                96,
                97,
                123,
                123,
                127,
                127,
                127,
                130,
                134,
                133,
                129,
                126,
                121,
                137,
                141,
                149,
                144,
                120,
                104,
                102,
                100,
                107,
                116,
                107,
                98,
                97,
                115,
                107,
                106,
                98
            ]
        }
    },
    "starttime": 1446102000,
    "timezone_history": [
        {
            "offset": -7,
            "start": 1446102000,
            "timezone": "America\/Los_Angeles"
        }
    ]
}

我如何获得"值"?

下的心率数据数组

如果我打印:

JSONObject a = new JSONObject(obj.getJSONObject("metrics").getJSONObject("heartrate"));

我得到:

{}

似乎JSONArray也不是正确的选择。我只想获得一系列可以使用的双打。谢谢!

2 个答案:

答案 0 :(得分:2)

JSON经验法则

  • '['表示JSONArray节点

  • 的开头
  • '{'代表JSONObject

如果您的JSON节点以 [ 开头,那么我们应该使用getJSONArray()方法。如果节点以 { 开头,那么我们应该使用getJSONObject()方法。

以下是获取Double Values的代码

   public static ArrayList<Double> getHeartRates(String jsonString) throws JSONException {
            ArrayList<Double> values = new ArrayList<>();
            // root JSON Object.
            JSONObject jsonObject = new JSONObject(jsonString);

            JSONObject metrics = jsonObject.getJSONObject("metrics");
            JSONObject heartRate = metrics.getJSONObject("heartrate");
            JSONArray valuesArray = heartRate.getJSONArray("values");

            for (int i = 0; i < valuesArray.length(); i++) {                                       
                values.add(valuesArray.getDouble(i));
            }

            return values;
        }

答案 1 :(得分:0)

我认为这应该可以胜任:

JSONObject main = new JSONObject(MyJsonString);
JSONArray values = main.getJSONObject("metrics")
                    .getJSONObject("heartrate").getJSONArray("values");