How to Convert HTML to JSON using Java

This brief article explains how to convert HTML to JSON using Java. It explains the environment setup, stepwise procedure, and a sample code to convert HTML to JSON using Java. However, any complicated or specialized application or plugin is not required to work with this feature on your end.

Steps to Convert HTML to JSON using Java

  1. Set up the IDE by configuring Aspose.Cells for Java to render HTML data to JSON
  2. Create a Workbook class object to load the HTML data
  3. Initialize an object of JsonSaveOptions class
  4. Declare a Range of cells and export it to JSON format
  5. Export the output JSON data

These steps iterate the process to develop HTML to JSON Java converter. Firstly, access the source HTML data and get the reference to its last cell. Subsequently, define a cell range and export it to JSON format.

Code to Transform HTML to JSON using Java

import com.aspose.cells.*;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class Main {
public static void main(String[] args) throws Exception // Convert HTML to JSON in Java
{
// Set the licenses
new License().setLicense("License.lic");
Workbook workbook = new Workbook("Sample.html");
// Get the last cell
Cell lastCell = workbook.getWorksheets().get(0).getCells().getLastCell();
// Set JsonSaveOptions
JsonSaveOptions options = new JsonSaveOptions();
Range range = workbook.getWorksheets().get(0).getCells().createRange(
0,
0,
lastCell.getRow() + 1,
lastCell.getColumn() + 1);
// Export JSON data to a string
String data = JsonUtility.exportRangeToJson(range, options);
try (Writer writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream("htmltojson.json"),
"utf-8"))) {
writer.write(data);
System.out.println("Done");
}
}}

This code snippet demonstrates how using Java HTML to JSON format converter can be created. First of all, a Workbook class object is used to load the source HTML format data. Next, define a range while specifying the cell indexes and convert it to JSON format. You can also customize the conversion process with different methods exposed by the JsonSaveOptions class like clearing data in the workbook, exporting as string, exporting nested structures, etc. based on your requirements.

This article has shown how to create HTML to JSON converter using Java. Besides, if you want to render TXT to JSON data then take a look at the article on how to convert TXT to JSON using Java.

 English