简体   繁体   English

如何将 JSOnObject 转换为数组

[英]How to convert JSOnObject to Array

i´m new to JSON and when trying to fetch data i'm getting the following error E/Volley: com.android.volley.ParseError: org.json.JSONException:我是 JSON 新手,在尝试获取数据时,我收到以下错误E/Volley: com.android.volley.ParseError: org.json.JSONException:

Edit:编辑:

Full StackTrace:完整的堆栈跟踪:

2020-11-10 20:06:48.606 10505-10505/com.madcoderz.jsonparsing E/Volley: com.android.volley.ParseError: org.json.JSONException: Value {"message":{"affenpinscher":[],"african":[],"airedale":[],"akita":[],"appenzeller":[],"australian":["shepherd"],"basenji":[],"beagle":[],"bluetick":[],"borzoi":[],"bouvier":[],"boxer":[],"brabancon":[],"briard":[],"buhund":["norwegian"],"bulldog":["boston","english","french"],"bullterrier":["staffordshire"],"cairn":[],"cattledog":["australian"],"chihuahua":[],"chow":[],"clumber":[],"cockapoo":[],"collie":["border"],"coonhound":[],"corgi":["cardigan"],"cotondetulear":[],"dachshund":[],"dalmatian":[],"dane":["great"],"deerhound":["scottish"],"dhole":[],"dingo":[],"doberman":[],"elkhound":["norwegian"],"entlebucher":[],"eskimo":[],"finnish":["lapphund"],"frise":["bichon"],"germanshepherd":[],"greyhound":["italian"],"groenendael":[],"havanese":[],"hound":["afghan","basset","blood","english","ibizan","plott","walker"],"husky":[],"keeshond":[],"kelpie":[],"komondor":[],"kuvasz":[],"labrador":[],"leonberg":[],"lhasa":[],"malamute":[],"malinois":[],"maltese":[],"mastiff":["bull","english","tibetan"],"mexicanhairless":[],"mix":[],"mountain":["bernese","swiss"],"newfoundland":[],"otterhound":[],"ovcharka":["caucasian"],"papillon":[],"pekinese":[],"pembroke":[],"pinscher":["miniature"],"pitbull":[],"pointer":["german","germanlonghair"],"pomeranian":[],"poodle":["miniature","standard","toy"],"pug":[],"puggle":[],"pyrenees":[],"redbone":[],"retriever":["chesapeake","curly","flatcoated","golden"],"ridgeback":["rhodesian"],"rottweiler":[],"saluki":[],"samoyed":[],"schipperke":[],"schnauzer":["giant","miniature"],"setter":["english","gordon","irish"],"sheepdog":["english","shetland"],"shiba":[],"shihtzu":[],"spaniel":["blenheim","brittany","cocker","irish","japanese","sussex","welsh"],"springer":["english"],"stbernard":[],"terrier":["american","australian","bedlington","border","dandie","fox","irish","kerryblue","lakeland","norfolk","norwich","patterdale","russell","scottish","sealyham","silky","tibetan","toy","westhighland","wheaten","yorkshire"],"vizsla":[],"waterdog":["spanish"],"weimaraner":[],"whippet":[],"wolfhound":["irish"]},"status":"success"} of type org.json.JSONObject cannot be converted to JSONArray

JSON Data : https://dog.ceo/api/breeds/list/all JSON 数据https : //dog.ceo/api/breeds/list/all

I've been diggin a lot here at SO but can´t seem to find the correct approach我在 SO 上进行了很多挖掘,但似乎找不到正确的方法

Here is the code i've writen so far:这是我到目前为止编写的代码:

 private void getData() {
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Loading...");
    progressDialog.show();

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            for (int i = 0; i < response.length(); i++) {
                try {
                    JSONObject jsonObject = response.getJSONObject(i);

                    Article article = new Article();
                    article.setImage(jsonObject.getString("image"));
                    article.setTitle(jsonObject.getString("title"));
                    article.setBody(jsonObject.getString("body"));
                    articles.add(article);


                } catch (JSONException e) {
                    e.printStackTrace();
                    progressDialog.dismiss();
                }
            }
            adaptor.setData(articles);
            adaptor.notifyDataSetChanged();
            progressDialog.dismiss();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Volley", error.toString());
            progressDialog.dismiss();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonArrayRequest);
}

} }

Te answer is that i was using the wrong URL and the JSON call was expecting a JSONArray instead of a JSONObject.答案是我使用了错误的 URL,并且 JSON 调用期望使用 JSONArray 而不是 JSONObject。 Here is the code that solved the problem:这是解决问题的代码:

private void fetchElements(){
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, JSON_URL,
            null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            try {
                JSONArray breedsList = response.getJSONArray("message");
                for (int i=0; i < breedsList.length(); i++){

                    Cat cat = new Cat();
                    cat.setCatBreed(breedsList.getString(i));

                    cats.add(cat);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
            catAdapter = new CatAdapter(getApplicationContext(), cats);
            recyclerView.setAdapter(catAdapter);
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    requestQueue.add(objectRequest);
}

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

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