简体   繁体   English

JSON VOLLEY PARSING错误

[英]JSON VOLLEY PARSING error

Today i discovered really dumb problem. 今天我发现了一个非常愚蠢的问题。

Here is my mainactivity: 这是我的主要活动:

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);
    }
} 

I need to parse data from this api to my application https://api.coinmarketcap.com/v2/ticker/ 我需要将数据从此api解析到我的应用程序https://api.coinmarketcap.com/v2/ticker/

I found problem when tried to compile and get data from json object but when i tried Log.d("Coins",coin.getName()); 我尝试编译并从json对象获取数据时发现问题,但是当我尝试Log.d(“ Coins”,coin.getName());时发现问题。 i don't get any names i get this Value: and whole json data (that is not what i wanted , i need only names so i think i made mistake in MainActivity where i try to grab "data" object i think i am getting it but i don't get full objects because i think i need code to read random numbers above coins id in api or below "data" 我没有任何名字我得到了这个值:和整个json数据(那不是我想要的,我只需要名字,所以我认为我在MainActivity中弄错了,我试图抓住“数据”对象,我认为我正在得到它,但我没有完整的对象,因为我认为我需要代码才能读取api中硬币ID上方或“数据”下方的随机数

So my question is how to get price,rank ,symbol etc from api i think i made mistake here : 所以我的问题是如何从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())); } 

Thanks guys for time to help me. 谢谢你们有时间帮助我。

ps my second question doesn't belongs here but i don't know why i can not compile android when i import PICASSO LIBARY ,, really strange thing... ps我的第二个问题不属于这里,但我不知道为什么当我导入PICASSO LIBARY时为什么我不能编译android,真的很奇怪...

If someone wanna join me on project message me here or on skype: drvenapila 如果有人想和我一起在这里或在Skype上给我发消息:drvenapila

Your line 你的线

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

..wants to parse the data object as an array. ..想将数据对象解析为数组。 If we look at the first lines of the JSON response from coinmarketcap.com/v2/ticker we see 如果我们看一下来自coinmarketcap.com/v2/ticker的JSON响应的第一行,我们会看到

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

..but if it was an array, it would go like "data": [ { ..但是,如果它是一个数组,它将像"data": [ {

"data" instead contains a Map<String,Object> where the Keys are the current ranking of the coin. 相反,“数据”包含Map<String,Object> ,其中“键”是硬币的当前排名。 Eg 1 : Bitcoin, 2 : Ethereum, 3 : Ripple 例如1:比特币,2:以太坊,3:波纹

So what you probably want is to get this Map out of "data" and then get the Object for each key(s) you desire. 因此,您可能想要的是从“数据”中获取此Map,然后为所需的每个键获取Object。

This may help you: Convert JSON to Map 这可能对您有帮助: 将JSON转换为Map

Trivia: Funny how each Coin-Object has an "id" which matches the keys of the map.. Indeed one would expect an array here. 琐事:有趣的是,每个硬币对象都有一个与映射键匹配的“ id”。确实,人们会期望在这里有一个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM