从另一个JSON数组中的JSON数组中检索多个JSON对象? - java

对于大学任务,我需要创建一个应用程序,该应用程序从著名的荷兰在线商店的API中检索产品数据。我需要将每个产品的标题,摘要,价格和图像URL存储到一个新的Product对象中。这些产品存储在ArrayList中,然后返回ArrayList。

产品数组中的每个产品都有一个称为“ images”的嵌套数组,其中包含6个产品图像。这些图像需要存储在我的Product对象的HashMap属性中,图像大小作为键,URL作为值。但是,我似乎无法正确解决。

查询“ pokemon”的JSON数据:https://api.bol.com/catalog/v4/search/?apikey=25C4742A92BF468EB2BD888FC8FBFF40&format=json&q=pokemon

产品类别:

package com.example.bolcombrowser.domain;

import java.util.Map;

public class Product {

    // Attributes
    private String mTitle;
    private String mSummary;
    private double mPrice;
    private Map < String, String > mImageUrls;

    // Constructor
    public Product(String mTitle, String mSummary, double mPrice, Map < String, String > mImageUrls) {
        this.mTitle = mTitle;
        this.mSummary = mSummary;
        this.mPrice = mPrice;
        this.mImageUrls = mImageUrls;
    }

    // Getters and Setters
    public String getmTitle() {
        return mTitle;
    }

    public void setmTitle(String mTitle) {
        this.mTitle = mTitle;
    }

    public String getmSummary() {
        return mSummary;
    }

    public void setmSummary(String mSummary) {
        this.mSummary = mSummary;
    }

    public double getmPrice() {
        return mPrice;
    }

    public void setmPrice(double mPrice) {
        this.mPrice = mPrice;
    }

    public Map < String, String > getImageUrls() {
        return mImageUrls;
    }

    public void setImageUrls(Map < String, String > imageUrls) {
        this.mImageUrls = imageUrls;
    }
}

parseJson方法:

public static ArrayList < Product > parseJson(String productJsonStr) throws JSONException {

    /* JSON array names. */
    final String BOL_PRODUCTS = "products";
    final String BOL_IMAGES = "images";
    final String BOL_OFFERS = "offers";

    /* JSON key names. */
    final String BOL_TITLE = "title";
    final String BOL_SUMMARY = "summary";
    final String BOL_OFFERDATA = "offerData";
    final String BOL_PRICE = "price";
    final String BOL_KEY = "key";
    final String BOL_URL = "url";

    /* Variables to store product data into, and is then used to create new Product objects. */
    String title;
    String summary;
    double price;
    Map < String, String > imageUrls = new HashMap < > ();

    /* ArrayList to store products into. */
    ArrayList < Product > productList = new ArrayList < > ();

    JSONObject productsJson = new JSONObject(productJsonStr);

    JSONArray productsArray = productsJson.getJSONArray(BOL_PRODUCTS);

    for (int i = 0; i < productsArray.length(); i++) {
        JSONObject product = productsArray.getJSONObject(i);

        /* Retrieve the title and summary of each product. */
        title = product.getString(BOL_TITLE);
        summary = product.getString(BOL_SUMMARY);

        JSONArray imagesArray = product.getJSONArray(BOL_IMAGES);

        for (int j = 0; j < imagesArray.length(); j++) {
            JSONObject image = imagesArray.getJSONObject(j);

            /* Retrieve each product's image sizes and URLs and store them into a HashMap. */
            String imageSize = image.getString(BOL_KEY);
            String imageUrl = image.getString(BOL_URL);

            imageUrls.put(imageSize, imageUrl);
        }

        JSONObject offerData = product.getJSONObject(BOL_OFFERDATA);
        JSONArray offers = offerData.getJSONArray(BOL_OFFERS);
        JSONObject offer = offers.getJSONObject(0);
        price = offer.getDouble(BOL_PRICE);

        productList.add(new Product(title, summary, price, imageUrls));
    }

    return productList;
}

onPostExecute方法:

@Override
protected void onPostExecute(String productData) {
    if (productData != null) {
        ArrayList < Product > productList;

        try {
            productList = JsonUtils.parseJson(productData);

            for (Product product: productList) {
                String title = product.getmTitle();
                String summary = product.getmSummary();
                double price = product.getmPrice();
                String hashMap = product.getImageUrls().toString();

                mTextViewOutput.append(title + "\n\n" + summary + "\n\n" + price + "\n\n" +
                    hashMap + "\n\n\n\n\n");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

当我测试我的应用程序时,它似乎已将最后一个产品的图像URL存储到每个产品的HashMap中:

从另一个JSON数组中的JSON数组中检索多个JSON对象? - java

我已经盯着我的代码好几个小时了,但我似乎找不到原因。我可能犯了一个非常愚蠢的错误,但是我似乎无法弄清楚到底是什么。

java大神给出的解决方案

您的Map<String, String> imageUrls = new HashMap<>();放在错误的位置。它应该在第一个for循环内,否则所有产品都使用相同的Map

...
for (int i = 0; i < productsArray.length(); i++) {
    Map<String, String> imageUrls = new HashMap<>();
...

顺便说一句,我建议使用gson库。它将使您的代码更少样板

java:继承 - java

有哪些替代继承的方法? java大神给出的解决方案 有效的Java:偏重于继承而不是继承。 (这实际上也来自“四人帮”)。他提出的理由是,如果扩展类未明确设计为继承,则继承会引起很多不正常的副作用。例如,对super.someMethod()的任何调用都可以引导您通过未知代码的意外路径。取而代之的是,持有对本来应该扩展的类的引用,然后委托给它。这是与Eric…

如何在JAVA中传递以逗号分隔的值作为函数参数的字符串 - java

我有一个可以接受任何数量的INTEGER参数的方法:pages(int,int...)此方法是选择PDF文件的某些页面。以以下字符串类型存储的书页:String pages = "1,2,3,6,9"; 我想将此字符串作为方法的参数看起来像:pages(1,2,3,6,9); java大神给出的解决方案 使用流可以很容易地做到这一点:St…

Java-如何将此字符串转换为日期? - java

我从服务器收到此消息,我不明白T和Z的含义,2012-08-24T09:59:59Z将此字符串转换为Date对象的正确SimpleDateFormat模式是什么? java大神给出的解决方案 这是ISO 8601标准。您可以使用SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM…

当回复有时是一个对象有时是一个数组时,如何在使用改造时解析JSON回复? - java

我正在使用Retrofit来获取JSON答复。这是我实施的一部分-@GET("/api/report/list") Observable<Bills> listBill(@Query("employee_id") String employeeID); 而条例草案类是-public static class…

从方法返回数组-Java - java

private static Coordinate[] getCircleCoordintaes() { Coordinate coordinates[] = {new Coordinate(0, 0)}; return coordinates; } 以上程序工作正常。在上面的程序中,返回的坐标数组首先初始化了数组使用这条线Coordinate coordi…