Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONException: Not a primitive array in parsing JSONArray

Tags:

json

android

JSON I'm dealing with:

[
  {
    "score":2.860397,
    "show": {
      "id": 82,
      "url": "http://www.tvmaze.com/shows/82/game-of-thrones",
      "name": "Game of Thrones",
      "type": "Scripted",
      "language": "English",
      "genres": [
        "Drama", "Adventure", "Fantasy"
      ],
      "status": "Running",
      "runtime": 60,
      "premiered": "2011-04-17",
      "schedule": {
        "time": "21:00",
        "days": [ "Sunday" ]
      },
      "rating": {
        "average": 9.4
      },
      "weight": 100,
      "network": {
        "id": 8,
        "name": "HBO",
        "country": {
          "name": "United States",
          "code": "US",  
          "timezone": "America/New_York"
        }
      },
      "webChannel": null,
      "externals": {
        "tvrage": 24493,
        "thetvdb": 121361,
        "imdb": "tt0944947"
      },
      "image": { 
        "medium": "http://tvmazecdn.com/uploads/images/medium_portrait/53/132622.jpg",
        "original": "http://tvmazecdn.com/uploads/images/original_untouched/53/132622.jpg"
      },           
      "summary": "<p>Based on the bestselling book series A Song of Ice and Fire by George R.R. Martin, this sprawling new HBO drama is set in a world where summers span decades and winters can last a lifetime. From the scheming south and the savage eastern lands, to the frozen north and ancient Wall that protects the realm from the mysterious darkness beyond, the powerful families of the Seven Kingdoms are locked in a battle for the Iron Throne. This is a story of duplicity and treachery, nobility and honor, conquest and triumph. In the <strong><em>\"Game of Thrones\"</em></strong>, you either win or you die.</p>",
      "updated": 1462561599,
      "_links": {
        "self": {
          "href": "http://api.tvmaze.com/shows/82"
        }, 
        "previousepisode": {  
          "href": "http://api.tvmaze.com/episodes/664672"
         },
        "nextepisode": {
          "href": "http://api.tvmaze.com/episodes/664673"
        }
      }
    } 
  }
]

My code:

JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, final_url, (String)null,
    new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            try {
                JSONArray jArray = new JSONArray(response);

                for(int i=0; i<jArray.length(); i++) {
                    JSONObject json_object = (JSONObject)jArray.get(i);
                    String name = json_object.getString("name");
                    System.out.println(name);
                }
            } catch(JSONException e) {
                System.out.println(e);
            }
        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println(error);
        }
    }
);

I've seen there are many questions like that but most of them deal with JSONObject not JSONArray and I didn't find solution that would work for me.

I'm still getting error mentioned in title. Any help?

UPDATE: Tried everything except gson so far and still doesn't work. Stack trace is:

05-08 14:18:14.790 2628-2628/com.example.user.test W/System.err:     org.json.JSONException: Not a primitive array: class org.json.JSONArray
05-08 14:18:14.790 2628-2628/com.example.user.test W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:116)
05-08 14:18:14.790 2628-2628/com.example.user.test W/System.err:     at com.example.user.test.SearchActivity$2$override.onResponse(SearchActivity.java:134)
05-08 14:18:14.790 2628-2628/com.example.user.test W/System.err:     at com.example.user.test.SearchActivity$2$override.access$dispatch(SearchActivity.java)
05-08 14:18:14.790 2628-2628/com.example.user.test W/System.err:     at com.example.user.test.SearchActivity$2.onResponse(SearchActivity.java:0)
05-08 14:18:14.790 2628-2628/com.example.user.test W/System.err:     at com.example.user.test.SearchActivity$2.onResponse(SearchActivity.java:115)
05-08 14:18:14.790 2628-2628/com.example.user.test W/System.err:     at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:72)
05-08 14:18:14.790 2628-2628/com.example.user.test W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
05-08 14:18:14.790 2628-2628/com.example.user.test W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
05-08 14:18:14.790 2628-2628/com.example.user.test W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
05-08 14:18:14.790 2628-2628/com.example.user.test W/System.err:     at android.os.Looper.loop(Looper.java:135)
05-08 14:18:14.790 2628-2628/com.example.user.test W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5254)
05-08 14:18:14.797 2628-2628/com.example.user.test W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
05-08 14:18:14.797 2628-2628/com.example.user.test W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
05-08 14:18:14.801 2628-2628/com.example.user.test W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
05-08 14:18:14.801 2628-2628/com.example.user.test W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

UPDATE 2: My wole searchActivity.java Maybe mistake is somewhere else(I removed array to see if it changes anything but nope):

public class SearchActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);



    final EditText editText = (EditText) findViewById(R.id.searchView);
    editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String query = editText.getText().toString();
                //doMySearch(query);
                clearQuery(query);
                handled = true;
            }
            return handled;
        }
    });


}

public void clearQuery(String query) {
    query = query.replaceAll("[^\\w\\s]","").replaceAll("\\s+","-"); //TVMaze API uses "-" as spaces

    doMySearch(query);

}


public void doMySearch(String query) {
    System.out.println("print if doMySearch was opened");
    System.out.println(query);
    List<Show> subscribedShowsList = new ArrayList<Show>();

    String url = "http://api.tvmaze.com/search/shows?q=";
    String final_url = url + query;

    RequestQueue mRequestQueue;

// Instantiate the cache
    Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap

// Set up the network to use HttpURLConnection as the HTTP client.
    Network network = new BasicNetwork(new HurlStack());

// Instantiate the RequestQueue with the cache and network.
    mRequestQueue = new RequestQueue(cache, network);



    JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, final_url, (String)null,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    System.out.println("print if we got to onResponse");
                    try {
                        JSONArray jArray = new JSONArray(response);

                        JSONObject joParent = response.getJSONObject(0);
                        JSONObject joShow = joParent.getJSONObject("show");
                        String name = joShow.getString("name");
                        System.out.println(name);

                    } catch(JSONException e) {
                        e.printStackTrace();

                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    System.out.println(error);
                }
            });
    mRequestQueue.add(request);
    mRequestQueue.start();
}

}

like image 755
dddeee Avatar asked Feb 27 '26 03:02

dddeee


1 Answers

Hope this helps.

try {    

  JSONObject joParent = response.getJSONObject(0);

  JSONObject joShow = joParent.getJSONObject("show");

  String name = joShow.getString("name");

} catch (JSONException e) {
   e.printStackTrace();
} 
like image 159
Harsh4789 Avatar answered Feb 28 '26 19:02

Harsh4789