【问题标题】:Parsing Json "nameless" array data解析 Json“无名”数组数据
【发布时间】:2019-04-23 16:34:26
【问题描述】:

我得到了这个无名的 json 数组

[ { "symbol": "AAPL", "price": 207.1, "updated_at": "2019-04-23 16:26:09" }, { "symbol": "FB", "price": 183.12, "updated_at": "2019-04-23 16:26:09" } ]

但我的代码使用命名数组,如下所示:

{
  "stocks": [
    {
      "symbol": "AAPL",
      "price": 205.98,
      "updated_at": "2019-04-23 15:18:25"
    },
    {
      "symbol": "FB",
      "price": 182.99,
      "updated_at": "2019-04-23 15:18:25"
    }
  ]
}

我不知道如何解析无名数组。它只有在命名时才有效,像这样(我将json数据数组命名为stocks)。

  try {
                            JSONArray jsonArray = response.getJSONArray("stocks");

如何使它与无名数组一起使用? 我想使用第一个注释掉的 url。

    private void jsonParse() {
       // String url = "https://financialmodelingprep.com/api/company/real-time-price/AAPL,FB,GOOG,RHT,NOK,INTC?datatype=json";
       String url = "https://api.myjson.com/bins/134wfc";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        //I call the array stocks, but it doesn't have a name from the server, so it wont show.
                        try {
                            JSONArray jsonArray = response.getJSONArray("stocks");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject stock = jsonArray.getJSONObject(i);

                                String symBol = stock.getString("symbol");
                                int value = stock.getInt("price");

                                mTextViewResult.append(symBol + ", " + String.valueOf(value) + " $\n" );
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        mQueue.add(request);
    }
}

【问题讨论】:

  • 只是猜测...由于响应是 JSONArray,我的猜测是 new Response.Listener&lt;JSONObject&gt;public void onResponse(JSONObject response) { 应该将 JSONObject 替换为 JSONArray。此外,JsonObjectRequest request = new JsonObjectRequest 可能需要更改为请求数组的内容。检查是否有JsonArrayRequest

标签: java android json parsing


【解决方案1】:

您可以按照示例中提供的方式直接请求 JSONArray。像这样:

JsonArrayRequest req = new JsonArrayRequest(Request.Method.GET, url, null,,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());

                        try {
                            // Parsing json array response
                            // loop through each json object
                            for (int i = 0; i < response.length(); i++) {

                                JSONObject object = (JSONObject) response
                                        .get(i);

                                //do rest of the code

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }

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

                    }
                });

【讨论】:

    【解决方案2】:

    您可以使用 .contains() 方法来检查数组位置是否具有您要获取的唯一值或键或字符串。

    看看这个例子。

    public void retrieve(final ListView gv, final ProgressBar myProgressBar) {
            final ArrayList<Teacher> teachers = new ArrayList<>();
    
            myProgressBar.setIndeterminate(true);
            myProgressBar.setVisibility(View.VISIBLE);
            StringRequest stringRequest = new StringRequest(Request.Method.GET, PHP_MYSQL_SITE_URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Teacher teacher;
                    try {
    
                        JSONArray jsonArray = new JSONArray(response);
    
                        for (int i = 0; i < jsonArray.length(); i++) {
    
                            JSONObject jsonObject;
                            jsonObject = jsonArray.getJSONObject(i);
    
                            if (!jsonObject.getString("shopName").contains(strUserName)) {
    
                            } else {
    
    
                                String name = jsonObject.getString("productName");
                                String description = jsonObject.getString("description");
                                String price = "Ksh " + jsonObject.getString("sellingPrice");
                                String productStatus = jsonObject.getString("productStatus");
                                String imageURL = jsonObject.getString("imagePath");
                                String buyingPrice = jsonObject.getString("buyingPrice");
                                String category = jsonObject.getString("category");
                                String brandName = jsonObject.getString("brandName");
                                String ID = jsonObject.getString("ID");
    
                                teacher = new Teacher(name, description, price, productStatus, brandName, buyingPrice, category,ID, imgUrl + "/uploads/" + imageURL);
                                teachers.add(teacher);
                            }
    
                            //SET TO SPINNER
                            adapter = new GridViewAdapter(c, teachers);
                            gv.setAdapter(adapter);
                            myProgressBar.setVisibility(View.GONE);
                        }
    
                    } catch (JSONException e) {
    
                        myProgressBar.setVisibility(View.GONE);
                        Toast.makeText(c, "GOOD RESPONSE BUT JAVA CAN'T PARSE JSON IT RECEIEVED. "+e.getMessage(), Toast.LENGTH_LONG).show();
                    }
    
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Toast.makeText(c, "UNSUCCESSFUL :  ERROR IS : "+volleyError.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
    
            RequestQueue requestQueue = Volley.newRequestQueue(ItemsActivity.this);
            requestQueue.add(stringRequest);
    
    
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      相关资源
      最近更新 更多