So, I'm encountering this weird problem: I'm using the Woocommerce Rest API and I need to get the src from the "images"-array.
I'v already tried to save the images-array in an other array, but then I have no idea how to get the "src" from the array:
try {
ConnectionRequest r = new ConnectionRequest();
r.setPost(false);
r.setUrl("https://" + tokens.getShop_name_token() + ".ch/wp-json/wc/v3/products?consumer_key=" + tokens.getConsumer_key_token() + "&consumer_secret=" + tokens.getSecret_key_token());
NetworkManager.getInstance().addToQueueAndWait(r);
Map<String, Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
//JSON Filter
ArrayList<Map<String, String>> myList = (ArrayList<Map<String, String>>) result.get("root");
for (int i = 0; i < myList.size(); i++) {
Map<String, String> dtls = myList.get(i);
productsArr.add(dtls.get("name"));
productStock.add(dtls.get("stock_status"));
productDateCreated.add(dtls.get("date_created"));
//TODO: Filter out image-soure
productImages.add(dtls.get("images"));
}
System.out.println(productImages);
Output: [[], [], [], [{id=16.0, date_created=2018-11-08T15:21:14, date_created_gmt=2018-11-08T15:21:14, date_modified=2018-11-08T15:21:14, date_modified_gmt=2018-11-08T15:21:14, src=https://website.com/wp-content/uploads/2018/11/1.jpg, name=Vneck Tshirt, alt=}], [{id=15.0, date_created=2018-11-08T15:21:14, date_created_gmt=2018-11-08T15:21:14, date_modified=2018-11-08T15:21:14, date_modified_gmt=2018-11-08T15:21:14, src=https://website.com/wp-content/uploads/2018/11/21.jpg, name=Tshirt, alt=}]]
I got this far. Now my question is: How can I filter out the index to get the "src" of the image?
As you use the rather minimally-featured com.codename1.io.JSONParser
JSON parser, which parses JSON to a Map<String, Object>
and nothing else, then what you want to do is convert the Object
that you get selecting a value to the expected type, and repeat from there.
If the top-level JSON object is an array, then a special "root"
element is created, which is what you are getting here. That means that the structure of your JSON is parsed as this:
{
"root": [
{
"name": <str>,
"stock_status": <???>,
"date_created": <str>,
"images":
{
"id": <num>,
"date_*": <str>,
"src": <str>,
"name": <str>,
"alt": <str>
}
]
}
]
}
So, to extract an image's src
, you have extracted the "root"
array and iterated over it. Instead of casting the results to Map<String, String>
however, you want to keep them as Map<String, Object>
:
for (const Map<String, Object> element : (List<Map<String, Object>>) result.get("root")) {
// The "element" object has an "images" value that is a list of objects
for (const Map<String, Object> image : (List<Map<String, Object>>) element.get("images")) {
// Save the "src" field of each image
productImages.add((String) image.get("src"));
}
}