2017-09-14 54 views
0

我正在構建使用http請求消耗Web API的android應用程序。我已經提出要求很容易,一切工作正常,但我找不到一種方法來轉換JSONArray我進入單浮點x,浮點y值。 歡迎任何幫助。如何將JSONArray轉換爲字符串/浮點值

如何API的樣子: enter image description here

我的代碼:

  @Override 
     public void onResponse(Call call, Response response) throws IOException { 

      try { 
       JSONObject jsonObj = new JSONObject(response.body().string()); 

       // Getting JSON Array node 
       JSONArray price = jsonObj.getJSONArray("price"); 



       for(int I = 0; I < price.length(); I++) 
       { 




        Float x ; 
        Float y ; 

        values.add(new Entry(x,y)); // add one entry per hour 


       } 

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


     } 
    }); 

回答

1

只要您可以使用以下方法:

JsonArray jArr = price.getJSONArray(I); 
values.add(new Entry((float)jArr.getDouble(0), (float)jArr.getDouble(1))); 

另外,price您需要檢索應該在的JSONObject代替另一個陣列。

+0

感謝響應! new Entry只接受Float值,但沒有getFloat選項,我該如何實現? –

+1

@VaclovasRekašiusJr。你可以改變Entry類型,任何方式檢查更新,你都可以獲得float的值。 – Ibrahim

+0

感謝您的回覆,真的幫了我很多。但更新你的答案,改變這條線 values.add(new Entry((float)jArr.getDouble(0),(float)jArr.getDouble(1))); 刪除拳擊,只是鑄造浮動工作正常。再次感謝。 –

1

你有沒有試着用這樣的:

private void getPricesArray(){ 
    ArrayList<Double[]> pricesDoubleArray = new ArrayList<>(); 
    for (int index = 0; index < pricesDoubleArray.size(); index++) { 
     pricesDoubleArray.get(index)[0] = Double.valueOf(16748584949L); // 
     pricesDoubleArray.get(index)[1] = 4506.45; // 
    } 
} 
+0

不,但我會看看,謝謝你的回答! –