簡體   English   中英

JSON VOLLEY PARSING錯誤

[英]JSON VOLLEY PARSING error

今天我發現了一個非常愚蠢的問題。

這是我的主要活動:

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private CoinRecyclerViewAdapter coinRecyclerViewAdapter;
    private List<Coin> coinList;
    private RequestQueue queue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        queue= Volley.newRequestQueue(this);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        recyclerView=findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        coinList=new ArrayList<>();

        Prefs prefs = new Prefs(MainActivity.this);
        String search = prefs.getSearch();
        getCoins(search);

    }

    //get coins
    public List<Coin> getCoins(
            String searchTerm
    ){
        coinList.clear();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                Constants.URL_LEFT
                //searchTerm+Constants.URL_RIGHT
                , new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {

                    JSONArray coinsArray=response.getJSONArray("data");

                    for (int i = 0; i < coinsArray.length(); i++){

                        JSONObject coinObj = coinsArray.getJSONObject(i);

                        Coin coin = new Coin();
                        coin.setName(coinObj.getString("name"));
                        coin.setSymbol(coinObj.getString("symbol"));
                        coin.setPrice(coinObj.getDouble("price"));
                        coin.setRank(coinObj.getInt("rank"));
                        coin.setPercentChange24h(coinObj.getDouble("percent_change_24h"));
                        coin.setMarketCap(coinObj.getDouble("market_cap"));
                        //coin.setPriceBtc(coinObj.getFloat("price_btc"));
                        coin.setTotalSupply(coinObj.getLong("total_supply"));
                        Log.d("kreten","kreten");
                        Log.d("coins:",String.valueOf(coin.getPrice()));


                    }

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

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(jsonObjectRequest);
        return coinList;
    }






    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
} 

我需要將數據從此api解析到我的應用程序https://api.coinmarketcap.com/v2/ticker/

我嘗試編譯並從json對象獲取數據時發現問題,但是當我嘗試Log.d(“ Coins”,coin.getName());時發現問題。 我沒有任何名字我得到了這個值:和整個json數據(那不是我想要的,我只需要名字,所以我認為我在MainActivity中弄錯了,我試圖抓住“數據”對象,我認為我正在得到它,但我沒有完整的對象,因為我認為我需要代碼才能讀取api中硬幣ID上方或“數據”下方的隨機數

所以我的問題是如何從api獲取價格,等級,符號等,我認為我在這里犯了錯誤:

  //get coins public List<Coin> getCoins( String searchTerm ){ coinList.clear(); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, Constants.URL_LEFT //searchTerm+Constants.URL_RIGHT , new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray coinsArray=response.getJSONArray("data"); for (int i = 0; i < coinsArray.length(); i++){ JSONObject coinObj = coinsArray.getJSONObject(i); Coin coin = new Coin(); coin.setName(coinObj.getString("name")); coin.setSymbol(coinObj.getString("symbol")); coin.setPrice(coinObj.getDouble("price")); coin.setRank(coinObj.getInt("rank")); coin.setPercentChange24h(coinObj.getDouble("percent_change_24h")); coin.setMarketCap(coinObj.getDouble("market_cap")); //coin.setPriceBtc(coinObj.getFloat("price_btc")); coin.setTotalSupply(coinObj.getLong("total_supply")); Log.d("kreten","kreten"); Log.d("coins:",String.valueOf(coin.getPrice())); } 

謝謝你們有時間幫助我。

ps我的第二個問題不屬於這里,但我不知道為什么當我導入PICASSO LIBARY時為什么我不能編譯android,真的很奇怪...

如果有人想和我一起在這里或在Skype上給我發消息:drvenapila

你的線

 JSONArray coinsArray=response.getJSONArray("data");

..想將數據對象解析為數組。 如果我們看一下來自coinmarketcap.com/v2/ticker的JSON響應的第一行,我們會看到

{
"data": {
    "1": {
        "id": 1, 
        "name": "Bitcoin", 
        "symbol": "BTC", 
        "website_slug": "bitcoin", 
        "rank": 1, 

..但是,如果它是一個數組,它將像"data": [ {

相反,“數據”包含Map<String,Object> ,其中“鍵”是硬幣的當前排名。 例如1:比特幣,2:以太坊,3:波紋

因此,您可能想要的是從“數據”中獲取此Map,然后為所需的每個鍵獲取Object。

這可能對您有幫助: 將JSON轉換為Map

瑣事:有趣的是,每個硬幣對象都有一個與映射鍵匹配的“ id”。確實,人們會期望在這里有一個數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM