How jspoon works: Mapping HTML to Java objects
masterjspoon parses HTML into Java objects using CSS selectors. To use it, follow these steps:
- Create a Data Class: Define a class with a default constructor. Annotate the fields you want to extract with the
@Selectorannotation, providing the CSS selector as the value. - Initialize Jspoon: Use
Jspoon.create()to get a jspoon instance. - Create an Adapter: Use
jspoon.adapter(YourClass.class)to create anHtmlAdapterspecifically for your class. - Parse HTML: Call
htmlAdapter.fromHtml(htmlContent)to transform an HTML string into an instance of your class.
Note: jspoon looks for the first occurrence of the selector in the HTML and sets its value to the field.
class Page {
@Selector("#title") String title;
@Selector("li.a") List<Integer> intList;
@Selector(value = "#image1", attr = "src") String imageSource;
}
Jspoon jspoon = Jspoon.create();
HtmlAdapter<Page> htmlAdapter = jspoon.adapter(Page.class);
Page page = htmlAdapter.fromHtml(htmlContent);