如何获取并解析此JSON对象到Android textview

时间:2017-10-13 09:23:11

标签: java android json

我使用的是 CryptoCompare 提供的API。我需要从此JSON对象获得符号价格

{
  "Response": "Success",
  "Message": "Do not take life too seriously. You will never get out of it alive.",
  "Data": [
    {
      "Symbol": "USD",
      "Price": 5660.94,
      "Open24Hour": 5155.13,
      "LastUpdateTS": 1507885905,
      "Volume24Hours": 222438.875,
      "Volume24HoursTo": 1214073220
    },
    {
      "Symbol": "EUR",
      "Price": 4757.16,
      "Open24Hour": 4318.19,
      "LastUpdateTS": 1507885905,
      "Volume24Hours": 26488.4023,
      "Volume24HoursTo": 120264888
    }
  ],
  "Type": 100
}

3 个答案:

答案 0 :(得分:2)

我建议您将数据存储到 List

因此,初始化两个 List

List<String> symbol = new ArrayList<String>();
List<String> price = new ArrayList<String>();

然后在这里你可以存储数据

try {

    JSONObject json = new JSONObject(response);
    JSONArray jArray = json.getJSONArray("Data");
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject object = jsonArray.getJSONObject(i);
        symbol.add(object.getString("Symbol"));
        price.add(object.getString("Price"));

    }

} catch (JSONException e) {
    e.printStackTrace();
}

这可能对您有所帮助

答案 1 :(得分:1)

怎么做?

  • 如果您在代码中遇到{},则可以使用JSONObject对其进行解析。

  • 如果您在代码中遇到[],则可以使用JSONArray对其进行解析。

  • 如果您在代码中遇到[],则可以使用for loop获取价值。

  • 您应该在代码中使用try catch

试试这个。

try {
        JSONObject jsonObject = new JSONObject(response);
        String Response = jsonObject.optString("Response");
        JSONArray Data = jsonObject.optJSONArray("Data");
        for (int i = 0; i < Data.length(); i++) {
            JSONObject jo = Data.optJSONObject(i);
            String Symbol = jo.optString("Symbol");
            String Price = jo.optString("Price");
            String Open24Hour = jo.optString("Open24Hour");
            String LastUpdateTS = jo.optString("LastUpdateTS");
            String Volume24Hours = jo.optString("Volume24Hours");
            String Volume24HoursTo = jo.optString("Volume24HoursTo");
        }
} catch (JSONException e) {
        e.printStackTrace();
}

答案 2 :(得分:0)

检查出来

try {

            JSONObject objresponse=new JSONObject("{\"Response\":\"Success\",\"Message\":\"Do not take life too seriously. You will never get out of it alive.\",\"Data\":[{\"Symbol\":\"USD\",\"Price\":5660.94,\"Open24Hour\":5155.13,\"LastUpdateTS\":1507885905,\"Volume24Hours\":222438.875,\"Volume24HoursTo\":1.21407322E+09},{\"Symbol\":\"EUR\",\"Price\":4757.16,\"Open24Hour\":4318.19,\"LastUpdateTS\":1507885905,\"Volume24Hours\":26488.4023,\"Volume24HoursTo\":120264888.0}],\"Type\":100}");
            JSONArray arrayData=objresponse.getJSONArray("Data");
            for (int i=0;i<arrayData.length();i++){
                JSONObject obj=arrayData.getJSONObject(i);
                String symbol=obj.getString("Symbol");
                float price=(float)obj.getLong("Price");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }