【问题标题】:JSON VOLLEY PARSING errorJSON VOLLEY 解析错误
【发布时间】:2018-05-03 00:41:04
【问题描述】:

今天我发现了一个非常愚蠢的问题。

这是我的主要活动:

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


                    }

感谢大家抽时间帮助我。

附言我的第二个问题不属于这里,但我不知道为什么我在导入 PICASSO LIBARY 时无法编译 android,真的很奇怪......

如果有人想加入我的项目,请在此处或 Skype 上给我留言:drvenapila

【问题讨论】:

    标签: java android json api android-volley


    【解决方案1】:

    你的线路

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

    ..想要将数据 object 解析为数组。 如果我们查看来自 coinmarketcap.com/v2/ticker 的 JSON 响应的第一行,我们会看到

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

    ..但如果它是一个数组,它会像"data": [ {

    “数据”包含Map&lt;String,Object&gt;,其中的键是硬币的当前排名。例如。 1:比特币,2:以太坊,3:瑞波币

    因此,您可能想要的是从“数据”中获取此 Map,然后为您想要的每个键获取对象。

    这可能会对您有所帮助:Convert JSON to Map

    琐事: 有趣的是,每个 Coin-Object 都有一个与地图键匹配的“id”。事实上,人们会期望这里有一个数组。

    【讨论】:

    • 请问您如何将其导入到我的源中?什么用什么命令,放在哪里?请帮我解决这个问题。我认为我应该使用 gson 而不是 volley,但我现在距离切换到 gson 太远了。你能解释一下如何将这些值放入 map 中吗?
    • 哼。类似HashMap&lt;String,Object&gt; result = new ObjectMapper().readValue(response.get("data"), HashMap.class);
    • 我真的没有得到我需要放的东西而不是 我也不明白为什么我没有那个方法 ObjectMapper,我需要把代码放在哪里MainActivity 中的 onResponse 还是在哪里?你能在 gmail cikatuna@gmail.com 或 skype 上加我吗: drvenapila 并尝试教我这个,我愿意为你的时间付钱。
    • 我给你发了邮件,现在要睡觉了。
    猜你喜欢
    • 1970-01-01
    • 2021-04-13
    • 2020-07-06
    • 2016-08-04
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多