如何检索JSONObject子字段?

时间:2019-12-12 22:52:39

标签: java android json retrofit

我一直在寻找这个问题。我正在使用汇率API,我需要一些有关json响应的帮助。我想获取日期和 CAD Double 值。

这是我拥有的JSONObject:

{"rates":{"2019-11-27":{"CAD":1.3266418385},
    "2019-11-28":{"CAD":1.3289413903},
    "2019-12-03":{"CAD":1.3320386596},
    "2019-12-02":{"CAD":1.3295835979},
    "2019-11-29":{"CAD":1.3307230013}},
    "start_at":"2019-11-27","base":"USD","end_at":"2019-12-03"}
  

我的活动

公共类ChartActivity扩展了AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chart);
        new GetServerData(this).execute();
    }

    private static class GetServerData extends AsyncTask<Integer, Void, List<BarEntry>> {
        private static final int TIMEOUT = 30000;
        private static final String BASE_URL = "https://api.exchangeratesapi.io/history?start_at" +
                "=2019-11-27&end_at=2019-12-03&base=USD&symbols=CAD";
        private WeakReference<ChartActivity> activityReference;

        GetServerData(ChartActivity context) {
            activityReference = new WeakReference<>(context);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<BarEntry> doInBackground(Integer... integers) {
            List<BarEntry> barEntries = new ArrayList<>();
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                    .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(true)
                    .build();
            Request request = new Request.Builder()
                    .url(BASE_URL)
                    .build();
            try {
                Response response = client.newCall(request).execute();
                Log.d("Response", response.toString());
                JSONObject object = new JSONObject(Objects.requireNonNull(response.body()).string());
                JSONObject rates = object.getJSONObject("rates");
                Iterator<String> iterator = rates.keys();
                while (iterator.hasNext()) {
                    /* what i should write here to get the date and double values which is in 
                     JSONObject.*/

                    //barEntries.add(new BarEntry(int required of date, float required of value ));
                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
                Log.d("ChartActivity", e.toString());
            }
            return barEntries;
        }

        @Override
        protected void onPostExecute(final List<BarEntry> result) {
            final ChartActivity activity = activityReference.get();
            if (activity == null || activity.isFinishing()) {
                return;
            }
            BarChart barChart = activity.findViewById(R.id.bar_chart);

            BarDataSet dataSet = new BarDataSet(result, "Growth");
            dataSet.setColors(ColorTemplate.COLORFUL_COLORS);
            BarData barData = new BarData(dataSet);
            barData.setBarWidth(0.9f);
            barChart.animateY(5000);
            barChart.setData(barData);
            barChart.setFitBars(true);
            Description description = new Description();
            description.setText("Growth rate per week");
            barChart.setDescription(description);
            barChart.invalidate();

        }
    }
}

如您所见,我想检索数据以显示图表 请帮忙!

1 个答案:

答案 0 :(得分:3)

您可以尝试一下。没有时间来测试它,但希望它会有所帮助:

JSONObject rates = object.getJSONObject("rates");
Iterator<String> iterator = rates.keys();
while (iterator.hasNext()) {
    String keyDate = iterator.next(); // the date
    String cad = rates.getJSONObject(keyDate).getString("CAD"); // the numeric
}

编辑:

这摆脱了JSON主题,但是可以这样将日期字符串转换为数字。您必须找出正确的日期格式。

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");  
try {  
    Date date = formatter.parse("31/03/2015");  
    System.out.println("Date as milliseconds from 1.1.1970: "+date.getTime());  
} catch (ParseException e) {e.printStackTrace();}