Hjson (Human JSON) configuration file format library for Java providing parsing and generation capabilities with human-friendly features.
—
Convert JSON values to various string formats and write to streams with configurable formatting options, supporting compact JSON, pretty-printed JSON, and human-readable Hjson output.
Convert JSON values to string representations with different formatting options.
/**
* Returns a JSON string representation of this value in compact format
* @return JSON string representation
*/
String toString();
/**
* Returns a string representation of this value in the specified format
* @param format the output format (PLAIN, FORMATTED, or HJSON)
* @return string representation in the specified format
*/
String toString(Stringify format);
/**
* Returns an Hjson string representation of this value with custom options
* @param options the Hjson formatting options
* @return Hjson string representation
*/
String toString(HjsonOptions options);Usage Examples:
import org.hjson.JsonObject;
import org.hjson.JsonArray;
import org.hjson.Stringify;
import org.hjson.HjsonOptions;
JsonObject person = new JsonObject()
.add("name", "John Doe")
.add("age", 30)
.add("active", true)
.add("skills", new JsonArray().add("Java").add("Python").add("JavaScript"));
// Compact JSON (default)
String compact = person.toString();
System.out.println(compact);
// Output: {"name":"John Doe","age":30,"active":true,"skills":["Java","Python","JavaScript"]}
// Pretty-printed JSON
String formatted = person.toString(Stringify.FORMATTED);
System.out.println(formatted);
// Output:
// {
// "name": "John Doe",
// "age": 30,
// "active": true,
// "skills": [
// "Java",
// "Python",
// "JavaScript"
// ]
// }
// Human-readable Hjson
String hjson = person.toString(Stringify.HJSON);
System.out.println(hjson);
// Output:
// {
// name: John Doe
// age: 30
// active: true
// skills: [
// Java
// Python
// JavaScript
// ]
// }
// Hjson with custom options
HjsonOptions options = new HjsonOptions();
String customHjson = person.toString(options);
System.out.println(customHjson);Write JSON values directly to output streams for efficient processing of large data.
/**
* Writes the JSON representation of this value to the given writer in compact format
* @param writer the writer to write this value to
* @throws IOException if an I/O error occurs in the writer
*/
void writeTo(Writer writer) throws IOException;
/**
* Writes the string representation of this value to the given writer in the specified format
* @param writer the writer to write this value to
* @param format the output format (PLAIN, FORMATTED, or HJSON)
* @throws IOException if an I/O error occurs in the writer
*/
void writeTo(Writer writer, Stringify format) throws IOException;
/**
* Writes the Hjson representation of this value to the given writer with custom options
* @param writer the writer to write this value to
* @param options the Hjson formatting options
* @throws IOException if an I/O error occurs in the writer
*/
void writeTo(Writer writer, HjsonOptions options) throws IOException;Usage Examples:
import org.hjson.JsonObject;
import org.hjson.JsonArray;
import org.hjson.Stringify;
import java.io.FileWriter;
import java.io.StringWriter;
import java.io.IOException;
JsonArray data = new JsonArray();
for (int i = 0; i < 1000; i++) {
JsonObject item = new JsonObject()
.add("id", i)
.add("name", "Item " + i)
.add("value", Math.random() * 100);
data.add(item);
}
// Write to file
try (FileWriter fileWriter = new FileWriter("output.json")) {
data.writeTo(fileWriter, Stringify.FORMATTED);
System.out.println("Data written to output.json");
} catch (IOException e) {
System.err.println("Failed to write file: " + e.getMessage());
}
// Write to string (for in-memory processing)
StringWriter stringWriter = new StringWriter();
try {
data.writeTo(stringWriter, Stringify.HJSON);
String result = stringWriter.toString();
System.out.println("Generated " + result.length() + " characters");
} catch (IOException e) {
System.err.println("Failed to write to string: " + e.getMessage());
}
// Write to different streams based on content type
JsonObject config = new JsonObject()
.add("environment", "production")
.add("debug", false);
// Compact JSON for APIs
StringWriter apiWriter = new StringWriter();
config.writeTo(apiWriter); // Default compact format
String apiResponse = apiWriter.toString();
// Human-readable Hjson for configuration files
try (FileWriter configWriter = new FileWriter("app.hjson")) {
config.writeTo(configWriter, Stringify.HJSON);
}Control the formatting and appearance of serialized output.
/**
* Enumeration of output formatting options
*/
enum Stringify {
/**
* Compact JSON format with no whitespace
* Minimal size, suitable for network transmission and storage
*/
PLAIN,
/**
* Pretty-printed JSON format with indentation and line breaks
* Human-readable, suitable for debugging and development
*/
FORMATTED,
/**
* Hjson format with human-friendly syntax
* Most readable, suitable for configuration files and documentation
*/
HJSON
}Format Comparison Examples:
import org.hjson.JsonObject;
import org.hjson.JsonArray;
import org.hjson.Stringify;
JsonObject sample = new JsonObject()
.add("config", new JsonObject()
.add("name", "My App")
.add("version", "1.0.0"))
.add("features", new JsonArray()
.add("authentication")
.add("logging")
.add("caching"));
// PLAIN format (compact)
String plain = sample.toString(Stringify.PLAIN);
// {"config":{"name":"My App","version":"1.0.0"},"features":["authentication","logging","caching"]}
// FORMATTED format (pretty JSON)
String formatted = sample.toString(Stringify.FORMATTED);
// {
// "config": {
// "name": "My App",
// "version": "1.0.0"
// },
// "features": [
// "authentication",
// "logging",
// "caching"
// ]
// }
// HJSON format (human-friendly)
String hjson = sample.toString(Stringify.HJSON);
// {
// config: {
// name: My App
// version: "1.0.0"
// }
// features: [
// authentication
// logging
// caching
// ]
// }
// Compare sizes
System.out.println("Plain: " + plain.length() + " chars");
System.out.println("Formatted: " + formatted.length() + " chars");
System.out.println("Hjson: " + hjson.length() + " chars");Fine-tune Hjson output with custom configuration options.
/**
* Configuration class for Hjson formatting options
*/
class HjsonOptions {
/**
* Creates default Hjson formatting options
*/
HjsonOptions();
/**
* Gets the array of Domain Specific Format providers for output
* @return array of DSF providers (may be null)
*/
IHjsonDsfProvider[] getDsfProviders();
/**
* Sets the Domain Specific Format providers for specialized value formatting
* @param providers array of DSF providers
*/
void setDsfProviders(IHjsonDsfProvider[] providers);
}Usage Examples:
import org.hjson.JsonObject;
import org.hjson.JsonValue;
import org.hjson.HjsonOptions;
import org.hjson.HjsonDsf;
// Create data with special values
JsonObject data = new JsonObject()
.add("normalNumber", 42)
.add("infinity", JsonValue.valueOf(Double.POSITIVE_INFINITY))
.add("hexValue", JsonValue.valueOf(255))
.add("nanValue", JsonValue.valueOf(Double.NaN));
// Default formatting
String defaultOutput = data.toString(Stringify.HJSON);
System.out.println("Default:");
System.out.println(defaultOutput);
// Custom formatting with DSF providers
HjsonOptions options = new HjsonOptions();
options.setDsfProviders(new IHjsonDsfProvider[] {
HjsonDsf.math(), // Format mathematical constants
HjsonDsf.hex(true) // Format numbers as hexadecimal when appropriate
});
String customOutput = data.toString(options);
System.out.println("\nWith DSF providers:");
System.out.println(customOutput);
// Output may include:
// {
// normalNumber: 42
// infinity: +Inf
// hexValue: 0xFF
// nanValue: NaN
// }import org.hjson.JsonObject;
import org.hjson.JsonArray;
import org.hjson.Stringify;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
public class ConfigWriter {
public static void writeAppConfig() {
JsonObject config = new JsonObject()
.add("app", new JsonObject()
.add("name", "My Application")
.add("version", "1.2.0")
.add("port", 8080))
.add("database", new JsonObject()
.add("host", "localhost")
.add("port", 5432)
.add("name", "myapp_db"))
.add("features", new JsonArray()
.add("authentication")
.add("logging")
.add("metrics"));
// Write human-readable configuration
try (FileWriter writer = new FileWriter("config.hjson")) {
config.writeTo(writer, Stringify.HJSON);
System.out.println("Configuration written to config.hjson");
} catch (IOException e) {
System.err.println("Failed to write config: " + e.getMessage());
}
// Write JSON for production deployment
try (FileWriter writer = new FileWriter("config.json")) {
config.writeTo(writer, Stringify.FORMATTED);
System.out.println("JSON configuration written to config.json");
} catch (IOException e) {
System.err.println("Failed to write JSON config: " + e.getMessage());
}
}
}import org.hjson.JsonObject;
import org.hjson.JsonArray;
import org.hjson.Stringify;
import java.io.StringWriter;
public class ApiResponseGenerator {
public static String generateUserListResponse(List<User> users) {
JsonObject response = new JsonObject()
.add("status", "success")
.add("total", users.size())
.add("page", 1)
.add("data", new JsonArray());
JsonArray userArray = response.get("data").asArray();
for (User user : users) {
JsonObject userObj = new JsonObject()
.add("id", user.getId())
.add("name", user.getName())
.add("email", user.getEmail())
.add("active", user.isActive());
userArray.add(userObj);
}
// Return compact JSON for API responses
return response.toString(Stringify.PLAIN);
}
public static void writeResponseToStream(JsonObject response, Writer writer)
throws IOException {
// Stream the response directly without loading into memory
response.writeTo(writer, Stringify.PLAIN);
}
}import org.hjson.JsonArray;
import org.hjson.JsonObject;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class DataExporter {
public static void exportLargeDataset(List<DataRecord> records, String filename)
throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
// Write array opening
writer.write("[\n");
for (int i = 0; i < records.size(); i++) {
DataRecord record = records.get(i);
JsonObject obj = new JsonObject()
.add("id", record.getId())
.add("timestamp", record.getTimestamp())
.add("data", record.getData());
// Write formatted JSON for readability
String jsonStr = obj.toString(Stringify.FORMATTED);
// Indent the object content
String[] lines = jsonStr.split("\n");
for (String line : lines) {
writer.write(" " + line + "\n");
}
// Add comma except for last element
if (i < records.size() - 1) {
writer.write(",\n");
}
}
writer.write("]\n");
}
}
}// For large objects, prefer streaming over string conversion
JsonObject largeObject = createLargeObject();
// Memory-efficient: streams directly to output
try (FileWriter writer = new FileWriter("large-output.json")) {
largeObject.writeTo(writer, Stringify.PLAIN);
}
// Memory-intensive: loads entire string into memory
String largeString = largeObject.toString(Stringify.PLAIN);
Files.write(Paths.get("large-output.json"), largeString.getBytes());// Performance ranking (fastest to slowest):
// 1. PLAIN - minimal processing, no whitespace
String fastest = value.toString(Stringify.PLAIN);
// 2. FORMATTED - adds indentation and line breaks
String medium = value.toString(Stringify.FORMATTED);
// 3. HJSON - most processing, format conversion
String slowest = value.toString(Stringify.HJSON);
// For high-performance scenarios, use PLAIN format
// For development and debugging, use FORMATTED or HJSONimport java.io.IOException;
import java.io.FileWriter;
public void safeWrite(JsonValue value, String filename) {
try (FileWriter writer = new FileWriter(filename)) {
value.writeTo(writer, Stringify.FORMATTED);
} catch (IOException e) {
// Log error and handle gracefully
logger.error("Failed to write JSON to file: " + filename, e);
throw new RuntimeException("Unable to save data", e);
}
}
public String safeToString(JsonValue value, Stringify format) {
try {
return value.toString(format);
} catch (Exception e) {
// Fallback to basic format on error
logger.warn("Failed to format with " + format + ", using PLAIN", e);
return value.toString(Stringify.PLAIN);
}
}Install with Tessl CLI
npx tessl i tessl/maven-org-hjson--hjson