简体   繁体   中英

How do I fill a List inside a for each loop?

I'm trying to convert the jackson JSON string of a POJO into a JSON file to import to MySQL.

try {
        //HtmlPage object contains the html code
        HtmlPage page = client.getPage(baseUrl);
        //System.out.println(page.asXml());

        //Selecting nodes with xpath
        List<HtmlElement> itemList = page.getByXPath("//tr[@class='athing']");

        List<HackerNewsItem> fullList = new ArrayList<>();

        if(itemList.isEmpty()) {
            System.out.println("No item found");
        }else {
            for(HtmlElement htmlItem : itemList){
                int position = Integer.parseInt(((HtmlElement) htmlItem.getFirstByXPath("./td/span")).asText().replace(".", ""));
                int id = Integer.parseInt(htmlItem.getAttribute("id"));
                String title =  ((HtmlElement) htmlItem.getFirstByXPath("./td[not(@valign='top')][@class='title']")).asText();
                String url = ((HtmlAnchor) htmlItem.getFirstByXPath("./td[not(@valign='top')][@class='title']/a")).getHrefAttribute();
                String author =  ((HtmlElement) htmlItem.getFirstByXPath("./following-sibling::tr/td[@class='subtext']/a[@class='hnuser']")).asText();
                int score = Integer.parseInt(((HtmlElement) htmlItem.getFirstByXPath("./following-sibling::tr/td[@class='subtext']/span[@class='score']")).asText().replace(" points", ""));

                HackerNewsItem hnItem = new HackerNewsItem(title, url, author, score, position, id);

                ObjectMapper mapper = new ObjectMapper();

                String jsonString = mapper.writeValueAsString(hnItem) ;


                System.out.println(jsonString);
                mapper.writeValue(Paths.get("hackernewsitem2.json").toFile(), fullList.add(hnItem));

            }
          
        }

    }catch (Exception e) {
        e.printStackTrace();
    }

The problem I have is that, even tho I'm returned the JSON String in console and that the .json file is created, MySQL workbench throws an error unhandled exception: object of type bool() has no length. as a json file with the line "true" is created.

If I do mapper.writeValue(Paths.get("hackernewsitem.json").toFile(), hnItem); The file is correctly imported but with no data in the db and only one line if seen as json.

My POJO

@Getter@Setter@AllArgsConstructor
public class HackerNewsItem {

    @JsonProperty("item_title")
    private String title;

    @JsonProperty("item_url")
    private String url;

    @JsonProperty("item_author")
    private String author;

    @JsonProperty("item_score")
    private int score;

    @JsonProperty("item_position")
    private int position;

    @JsonProperty("item_id")
    private int id;

}

You want to fill the list inside your for-loop? Actually you already created the fullList before the loop, so you'd just make use of it. Once you created the HackerNewsItem just add it to the list.

HackerNewsItem hnItem = new HackerNewsItem(...);
fullList.add(hnItem);

And when the for loop is finished, you have all the items in your fullList.

Edit: Do not save your list from within the loop. This will give you strange results. So move the ObjectMapper stuff below your loop. This part should look like

ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(hnItem) ;
System.out.println(jsonString);
mapper.writeValue(Paths.get("hackernewsitems.json").toFile(), fullList);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM