解析Json“无名”数组数据

时间:2019-04-23 16:34:27

标签: java android json parsing

我正在获取这个无名的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");

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

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

2 个答案:

答案 0 :(得分: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) {

                    }
                });

答案 1 :(得分:0)

您可以使用.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);



    }