#39 Rewrote JSON accessing

This commit is contained in:
Marvin Scham
2023-05-24 00:24:01 +02:00
parent c09127200b
commit 17bd6ab587

View File

@@ -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
}