0

I'm fairly new to Android Studio and Java, and I'm working on an app that takes data from Unsplash's API and displays it. However, I'm getting a JSON typeMismatch error, and I'm not sure how to correctly extract the data. Technically I'm getting back an array of JSONObjects, but I'm finding that simply changing JSONObject to JSONArray is not the correct approach.

I believe the problem is with the following lines of code: What I want to do is get the user (photographer) name and profile image, and the image they're posting.

Any help is greatly appreciated!

private NewPhotos getNewPhotos(String jsonData) throws JSONException {
  JSONObject unsplash = new JSONObject(jsonData);

  JSONObject user = unsplash.getJSONObject("user");

  return new NewPhotos();
}

This is the JSON I'm getting back

This is the error message

Biii
  • 3,041
  • 4
  • 9
  • 8

3 Answers3

1

You need first, cast JSON ARRAY.

You didn't put all json file, but it seems to be an array first.

private NewPhotos getNewPhotos(String jsonData) throws JSONException {
  JSONArray unsplash = new JSONArray(jsonData);

  for (int i = 0; i < unsplash.length(); i++) {
    JSONObject jsonObj = (JSONObject) unsplash.get(i);
    JSONObject user = jsonObj.getJSONObject("user");
    // Do something with user
  }

  // Your implementation
  return new NewPhotos();
}
Rafaela Lourenço
  • 1,126
  • 16
  • 33
0

This doesn't work for you? :

 JSONObject unsplash = new JSONObject(jsonData);
 JSONArray user = unsplash.getJSONArray("user");

Cause in your code you're trying to assign jsonArray to jsonObject.

MakinTosH
  • 623
  • 7
  • 12
0

You can't convery JSON Array into a Json object. Rafaela is right. You need to pass the string in Json array and then loop through each object to access user json.