From 17bd6ab5872f974165b069a4f8f444e4a46e037c Mon Sep 17 00:00:00 2001 From: Marvin Scham Date: Wed, 24 May 2023 00:24:01 +0200 Subject: [PATCH] #39 Rewrote JSON accessing --- .../api/client/AmazonProductDataSource.java | 39 ++++++++----------- 1 file changed, 16 insertions(+), 23 deletions(-) diff --git a/src/main/java/de/rwu/easydrop/api/client/AmazonProductDataSource.java b/src/main/java/de/rwu/easydrop/api/client/AmazonProductDataSource.java index 04613eb..dbbdc6d 100644 --- a/src/main/java/de/rwu/easydrop/api/client/AmazonProductDataSource.java +++ b/src/main/java/de/rwu/easydrop/api/client/AmazonProductDataSource.java @@ -7,8 +7,9 @@ import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; -import org.json.JSONException; -import org.json.JSONObject; +import com.jayway.jsonpath.JsonPath; +import com.jayway.jsonpath.PathNotFoundException; +import com.jayway.jsonpath.ReadContext; import de.rwu.easydrop.api.dto.ProductDTO; @@ -77,8 +78,7 @@ public final class AmazonProductDataSource implements DataSource { } reader.close(); - JSONObject offer = new JSONObject(response.toString()).getJSONObject("featuredOffer"); - buildProductDTO(product, offer); + buildProductDTO(product, response.toString()); } catch (IOException e) { throw new IllegalArgumentException("Couldn't fulfill Amazon API request"); } @@ -90,29 +90,22 @@ public final class AmazonProductDataSource implements DataSource { * Enriches a ProductDTO with API-gathered data. * * @param product Unfinished ProductDTO - * @param offer Product data + * @param json Product data * @return Finished ProductDTO */ - private ProductDTO buildProductDTO(final ProductDTO product, final JSONObject offer) { + public ProductDTO buildProductDTO(final ProductDTO product, final String json) { + String root = "$.featuredOffer."; + ReadContext ctx = JsonPath.parse(json); + try { product.setDataOrigin(DATA_ORIGIN); - product.setAvailable(offer - .getString("availability") - .equals("available")); - product.setCurrentPrice(offer - .getJSONObject("price") - .getJSONObject("value") - .getDouble("amount")); - product.setDeliveryPrice(offer - .getJSONArray("shippingOptions") - .getJSONObject(0) - .getJSONObject("shippingCost") - .getJSONObject("value") - .getDouble("amount")); - product.setMerchant(offer - .getJSONObject("merchant") - .getString("name")); - } catch (JSONException e) { + product.setAvailable( + ctx.read(root + "availability", String.class).equals("available")); + product.setCurrentPrice(ctx.read(root + "price.value.amount", double.class)); + product.setDeliveryPrice( + ctx.read(root + "shippingOptions[0].shippingCost.value.amount", double.class)); + product.setMerchant(ctx.read(root + "merchant.name", String.class)); + } catch (PathNotFoundException e) { // Pass, allow incomplete ProductDTO to pass for later validation }