Java:从多数组中提取索引src

时间:2019-01-18 11:15:54

标签: java woocommerce

因此,我遇到了一个奇怪的问题:我正在使用Woocommerce Rest API,我需要从“图像”数组中获取src。

我已经尝试过将images-array保存在另一个数组中,但是后来我不知道如何从该数组中获取“ src”:

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);
  

输出:[[],[],[],[{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   T恤,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 =}]]

我到这为止了。现在我的问题是:如何过滤索引以获得图像的“ src”?

1 个答案:

答案 0 :(得分:1)

当您使用功能最弱的com.codename1.io.JSONParser JSON解析器时,它将JSON解析为Map<String, Object>,除此之外,您只需将得到的Object转换为选择所需类型的值,然后从那里重复。

如果顶级JSON对象是一个数组,那么将创建一个特殊的"root"元素,这就是您要获得的内容。这意味着JSON的结构被解析为:

{
    "root": [
        {
            "name": <str>,
            "stock_status": <???>,
            "date_created": <str>,
            "images": 
                {
                    "id": <num>,
                    "date_*": <str>,
                    "src": <str>,
                    "name": <str>,
                    "alt": <str>
                }
            ]
        }
    ]
}

因此,要提取图像的src,请提取"root"数组并对其进行迭代。但是,您不想将结果强制转换为Map<String, String>,而是将其保留为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"));
    }
}