1

I'm trying to show some images from url that gives a JSON response.

My goal is to show

Items > adapted > url

In an imageview inside a ListView.

The response is complicated:

{
  "count": 84245,
  "items": [
    {
      "author": "pure julia",
      "category_id": 66,
      "content_type": "free",
      "cost": 0,
      "description": "lanterns, snow, light, winter, night",
      "downloads": 227,
      "for_adult_only": false,
      "id": 195651,
      "license": "Unsplash License",
      "min_cost_ends_at": "1970-01-01T00:00:00Z",
      "rating": 227,
      "source_link": "https://unsplash.com/@purejulia",
      "tags": [
        "lanterns",
        "snow",
        "light",
        "winter",
        "night"
      ],
      "uploaded_at": "2020-12-27T07:20:00+0300",
      "variations": {
        "adapted": {
          "resolution": {
            "height": 1920,
            "width": 1080
          },
          "size": 250268,
          "url": "url"
        }
Regex
  • 528
  • 4
  • 20
  • 1
    What have you tried?It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask]. – fredrik Dec 27 '20 at 16:31
  • I have tried many possible ways before asking, all of them return a null pointer exception – Regex Dec 27 '20 at 16:32

3 Answers3

4

In Java, one way to parse JSON is to use org.json.

Below I have an example of how you might use org.json.JSONObject to parse your JSON, retrieve the URL for each item in the JSON, and create a ListView for displaying all images.

I believe your items > adapted_landscape > url path is incorrect. I believe the correct path is items > variations > adapted_landscape > url.

In my example snippet below, the fetchJSON() function is assumed to fetch the JSON from the URL you provided, and return the JSON as a String.

try {

    // Fetch and parse the JSON
    String jsonStr = fetchJSON();
    JSONObject json = new JSONObject(jsonStr);

    // Get the items and number of items
    JSONArray items = json.getJSONArray("items");
    int numItems = json.getInt("count");

    // Create a List to store the ImageViews in
    List<ImageView> images = new ArrayList<>();

    // Loop over the items, adding each one to the images List
    for (int i = 0; i < numItems; ++i) {
        // Retrieve the URL
        String landscapeURL = items.getJSONObject(i)
                .getJSONObject("variations")
                .getJSONObject("adapted_landscape")
                .getString("url");

        // Create and add an ImageView for the image at the URL
        images.add(new ImageView(landscapeURL));
    }

    // Create the ListView
    ListView<ImageView> listView = new ListView<>(FXCollections.observableArrayList(images));

} catch (JSONException e) {
    // Handle any JSON exception that may have occurred, as appropriate for your use case
}

You will need the following import statements in your code:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

Two alternative libraries you might consider are Google GSON and Jackson. This answer has some examples for those libraries, and links to their GitHub repositories and maven pages.

Shane Bishop
  • 3,905
  • 4
  • 17
  • 47
  • Thanks for your well-explained answer, one last question. How do I convert this to a listmap so I can show images in a ListView? – Regex Dec 27 '20 at 20:21
  • I apologize for forgetting to show how to set up a `ListView` in the first version of my answer. I have updated my answer to explain how to create the `ListView`. – Shane Bishop Dec 28 '20 at 15:54
0

https://github.com/google/gson Use Gson converter Map classes like this

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Adapted {

@SerializedName("resolution")
@Expose
private Resolution resolution;
@SerializedName("size")
@Expose
private Integer size;
@SerializedName("url")
@Expose
private String url;

public Resolution getResolution() {
return resolution;
}

public void setResolution(Resolution resolution) {
this.resolution = resolution;
}

public Integer getSize() {
return size;
}

public void setSize(Integer size) {
this.size = size;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

}
-----------------------------------com.example.AdaptedLandscape.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class AdaptedLandscape {

@SerializedName("resolution")
@Expose
private Resolution_ resolution;
@SerializedName("size")
@Expose
private Integer size;
@SerializedName("url")
@Expose
private String url;

public Resolution_ getResolution() {
return resolution;
}

public void setResolution(Resolution_ resolution) {
this.resolution = resolution;
}

public Integer getSize() {
return size;
}

public void setSize(Integer size) {
this.size = size;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

}
-----------------------------------com.example.Example.java-----------------------------------

package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

@SerializedName("count")
@Expose
private Integer count;
@SerializedName("items")
@Expose
private List<Item> items = null;
@SerializedName("response_time")
@Expose
private String responseTime;

public Integer getCount() {
return count;
}

public void setCount(Integer count) {
this.count = count;
}

public List<Item> getItems() {
return items;
}

public void setItems(List<Item> items) {
this.items = items;
}

public String getResponseTime() {
return responseTime;
}

public void setResponseTime(String responseTime) {
this.responseTime = responseTime;
}

}
-----------------------------------com.example.Item.java-----------------------------------

package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Item {

@SerializedName("author")
@Expose
private String author;
@SerializedName("category_id")
@Expose
private Integer categoryId;
@SerializedName("content_type")
@Expose
private String contentType;
@SerializedName("cost")
@Expose
private Integer cost;
@SerializedName("description")
@Expose
private String description;
@SerializedName("downloads")
@Expose
private Integer downloads;
@SerializedName("for_adult_only")
@Expose
private Boolean forAdultOnly;
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("license")
@Expose
private String license;
@SerializedName("min_cost_ends_at")
@Expose
private String minCostEndsAt;
@SerializedName("rating")
@Expose
private Integer rating;
@SerializedName("source_link")
@Expose
private String sourceLink;
@SerializedName("tags")
@Expose
private List<String> tags = null;
@SerializedName("uploaded_at")
@Expose
private String uploadedAt;
@SerializedName("variations")
@Expose
private Variations variations;

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public Integer getCategoryId() {
return categoryId;
}

public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}

public String getContentType() {
return contentType;
}

public void setContentType(String contentType) {
this.contentType = contentType;
}

public Integer getCost() {
return cost;
}

public void setCost(Integer cost) {
this.cost = cost;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public Integer getDownloads() {
return downloads;
}

public void setDownloads(Integer downloads) {
this.downloads = downloads;
}

public Boolean getForAdultOnly() {
return forAdultOnly;
}

public void setForAdultOnly(Boolean forAdultOnly) {
this.forAdultOnly = forAdultOnly;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getLicense() {
return license;
}

public void setLicense(String license) {
this.license = license;
}

public String getMinCostEndsAt() {
return minCostEndsAt;
}

public void setMinCostEndsAt(String minCostEndsAt) {
this.minCostEndsAt = minCostEndsAt;
}

public Integer getRating() {
return rating;
}

public void setRating(Integer rating) {
this.rating = rating;
}

public String getSourceLink() {
return sourceLink;
}

public void setSourceLink(String sourceLink) {
this.sourceLink = sourceLink;
}

public List<String> getTags() {
return tags;
}

public void setTags(List<String> tags) {
this.tags = tags;
}

public String getUploadedAt() {
return uploadedAt;
}

public void setUploadedAt(String uploadedAt) {
this.uploadedAt = uploadedAt;
}

public Variations getVariations() {
return variations;
}

public void setVariations(Variations variations) {
this.variations = variations;
}

}
-----------------------------------com.example.Original.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Original {

@SerializedName("resolution")
@Expose
private Resolution__ resolution;
@SerializedName("size")
@Expose
private Integer size;
@SerializedName("url")
@Expose
private String url;

public Resolution__ getResolution() {
return resolution;
}

public void setResolution(Resolution__ resolution) {
this.resolution = resolution;
}

public Integer getSize() {
return size;
}

public void setSize(Integer size) {
this.size = size;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

}
-----------------------------------com.example.PreviewSmall.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class PreviewSmall {

@SerializedName("resolution")
@Expose
private Resolution___ resolution;
@SerializedName("size")
@Expose
private Integer size;
@SerializedName("url")
@Expose
private String url;

public Resolution___ getResolution() {
return resolution;
}

public void setResolution(Resolution___ resolution) {
this.resolution = resolution;
}

public Integer getSize() {
return size;
}

public void setSize(Integer size) {
this.size = size;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

}
-----------------------------------com.example.Resolution.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Resolution {

@SerializedName("height")
@Expose
private Integer height;
@SerializedName("width")
@Expose
private Integer width;

public Integer getHeight() {
return height;
}

public void setHeight(Integer height) {
this.height = height;
}

public Integer getWidth() {
return width;
}

public void setWidth(Integer width) {
this.width = width;
}

}


package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Resolution_ {

@SerializedName("height")
@Expose
private Integer height;
@SerializedName("width")
@Expose
private Integer width;

public Integer getHeight() {
return height;
}

public void setHeight(Integer height) {
this.height = height;
}

public Integer getWidth() {
return width;
}

public void setWidth(Integer width) {
this.width = width;
}

}


package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Resolution__ {

@SerializedName("height")
@Expose
private Integer height;
@SerializedName("width")
@Expose
private Integer width;

public Integer getHeight() {
return height;
}

public void setHeight(Integer height) {
this.height = height;
}

public Integer getWidth() {
return width;
}

public void setWidth(Integer width) {
this.width = width;
}

}


package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Resolution___ {

@SerializedName("height")
@Expose
private Integer height;
@SerializedName("width")
@Expose
private Integer width;

public Integer getHeight() {
return height;
}

public void setHeight(Integer height) {
this.height = height;
}

public Integer getWidth() {
return width;
}

public void setWidth(Integer width) {
this.width = width;
}

}


package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Variations {

@SerializedName("adapted")
@Expose
private Adapted adapted;
@SerializedName("adapted_landscape")
@Expose
private AdaptedLandscape adaptedLandscape;
@SerializedName("original")
@Expose
private Original original;
@SerializedName("preview_small")
@Expose
private PreviewSmall previewSmall;

public Adapted getAdapted() {
return adapted;
}

public void setAdapted(Adapted adapted) {
this.adapted = adapted;
}

public AdaptedLandscape getAdaptedLandscape() {
return adaptedLandscape;
}

public void setAdaptedLandscape(AdaptedLandscape adaptedLandscape) {
this.adaptedLandscape = adaptedLandscape;
}

public Original getOriginal() {
return original;
}

public void setOriginal(Original original) {
this.original = original;
}

public PreviewSmall getPreviewSmall() {
return previewSmall;
}

public void setPreviewSmall(PreviewSmall previewSmall) {
this.previewSmall = previewSmall;
}

}
Adnan
  • 7,825
  • 3
  • 23
  • 41
0

if you want to only parse the retrieved json Object to get a list of urls with out dealing with POJOs , you can use Jackson ObjectMapper to parse the incoming object and return a list of urls needed , the following function works on the same url you mentioned and returns a list of Urls of the images , you can modify it to get any data and any level in the json object :

public List<String> GetImageUrls() throws IOException {

    String requestUrl = "https://api.wallpaperscraft.com/images?screen[width]=1080&screen[height]=1920&sort=date&offset=0&types[]=free&types[]=private";
    ObjectMapper mapper = new ObjectMapper();
    List<String> urls = new ArrayList<>();

    Map<String, Object> variation;
    Map<String, Object> landscape;

    Map<String, Object> responseMap = mapper.readValue(new URL(requestUrl), new TypeReference<Map<String, Object>>() {

    });

    for (Object item : (List) responseMap.get("items")) {
        if (item instanceof Map) {
            variation = (Map<String, Object>) ((Map) item).get("variations");
            landscape = (Map<String, Object>) variation.get("adapted_landscape");
            urls.add((String) landscape.get("url"));
        }
    }

    return urls;
} 

Let me Know if it works for you !!!