BSON to JSON: Efficient Data Conversion with Java
Source: Dev.to
Converting BSON to JSON with Java
In this post you’ll learn two ways to read BSON documents and convert them to JSON:
- Using the MongoDB Java driver – query a live database.
- Reading and parsing local
.bsonfiles – work at the byte level.
1. Create a Sample Maven Project
mvn archetype:generate \
-DgroupId=com.your-domain \
-DartifactId=bson-to-json \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DinteractiveMode=false
2. Configure pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.your-domain</groupId>
<artifactId>bson-to-json</artifactId>
<version>1.0‑SNAPSHOT</version>
<packaging>jar</packaging>
<name>bson-to-json</name>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- MongoDB synchronous driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>5.3.1</version>
</dependency>
<!-- SLF4J no‑operation implementation (to silence logging) -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>2.0.9</version>
</dependency>
<!-- JUnit for testing -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Maven Exec Plugin – runs the main class -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<mainClass>com.your-domain.App</mainClass>
<skip>false</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
3. Example 1 – Export a Collection to JSON
Create (or replace) src/main/java/com/yourdomain/App.java with the following code:
package com.yourdomain;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.json.JsonWriterSettings;
import java.io.FileWriter;
import java.io.IOException;
public class App {
public static void main(String[] args) {
// Connection string – replace user, password, host, and db as needed
String uri = "mongodb://user:password@localhost:27017/?authSource=admin";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// Target database & collection
MongoDatabase database = mongoClient.getDatabase("company");
MongoCollection<Document> collection = database.getCollection("employees");
// Pretty‑print JSON
JsonWriterSettings settings = JsonWriterSettings.builder()
.indent(true)
.build();
try (FileWriter file = new FileWriter("employees.json")) {
file.write("[\n");
// Write each document as JSON, followed by a comma
for (Document doc : collection.find()) {
file.write(doc.toJson(settings) + ",\n");
}
// Close the JSON array
file.write("]");
System.out.println("Exported successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
What the code does
| Step | Description |
|---|---|
| Package declaration | package com.yourdomain; |
| Create a client | MongoClients.create(uri) – uses the connection string. |
| Select DB & collection | mongoClient.getDatabase("company") and getCollection("employees"). |
| Configure pretty printing | JsonWriterSettings.builder().indent(true).build(). |
| Write JSON array | Opens [ , writes each document with toJson(settings), then closes ]. |
Run the program with:
mvn exec:java
You’ll get a nicely formatted employees.json file in the project root.
4. Example 2 – Parse a Local .bson File
If you have a BSON file on disk and want to convert it to JSON without a running MongoDB instance, use the low‑level BSON API.
Create (or replace) src/main/java/com/yourdomain/App.java with the following code:
package com.yourdomain;
import org.bson.BsonBinaryReader;
import org.bson.Document;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.DocumentCodec;
import org.bson.io.ByteBufferBsonInput;
import org.bson.json.JsonWriterSettings;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class App {
public static void main(String[] args) throws IOException {
// Path to the .bson file you want to convert
String inputPath = "data.bson";
// Output JSON file
String outputPath = "data.json";
// Pretty‑print settings
JsonWriterSettings jsonSettings = JsonWriterSettings.builder()
.indent(true)
.build();
// Open the BSON file for reading
try (FileInputStream fis = new FileInputStream(inputPath);
FileChannel channel = fis.getChannel();
FileWriter writer = new FileWriter(outputPath)) {
writer.write("[\n"); // start JSON array
long fileSize = channel.size();
long position = 0;
boolean first = true;
while (position < fileSize) {
// ---- Read document length (first 4 bytes, little‑endian) ----
ByteBuffer lengthBuffer = ByteBuffer.allocate(4);
channel.read(lengthBuffer, position);
lengthBuffer.flip();
int docLength = lengthBuffer.getInt();
// ---- Read the whole document ----
ByteBuffer docBuffer = ByteBuffer.allocate(docLength);
channel.read(docBuffer, position);
docBuffer.flip();
// ---- Decode BSON → Document ----
DocumentCodec codec = new DocumentCodec();
Document doc = codec.decode(
new BsonBinaryReader(new ByteBufferBsonInput(docBuffer)),
DecoderContext.builder().build());
// ---- Write comma separator if needed ----
if (!first) {
writer.write(",\n");
}
first = false;
// ---- Write the JSON representation ----
writer.write(doc.toJson(jsonSettings));
// Move to the next document
position += docLength;
}
writer.write("\n]");
System.out.println("BSON file converted to JSON successfully!");
}
}
}
Explanation of the workflow
| Step | What happens |
|---|---|
| Read document length | The first 4 bytes of each BSON document encode its total size. |
| Read the full document | Using the length, allocate a ByteBuffer and read the whole BSON blob. |
| Decode | DocumentCodec together with BsonBinaryReader turns the binary data into a Document. |
| Convert to JSON | doc.toJson(JsonWriterSettings) produces pretty‑printed JSON. |
| Wrap in an array | The program writes [ at the start and ] at the end, inserting commas between documents. |
Run the program with Maven:
mvn exec:java
You’ll obtain data.json, a JSON array containing all documents stored in data.bson.
5. Recap
| Approach | When to use | Key classes |
|---|---|---|
| MongoDB driver | You have a running MongoDB instance and want to export a collection. | MongoClient, MongoDatabase, MongoCollection, Document, JsonWriterSettings |
| Byte‑level BSON parsing | You only have a .bson file (e.g., a backup) and no server. | FileChannel, ByteBuffer, BsonBinaryReader, DocumentCodec, JsonWriterSettings |
Both snippets produce a nicely formatted JSON array that can be consumed by any downstream system. Happy coding!
BSON → JSON Conversion Example (Java)
import com.mongodb.MongoClientSettings;
import org.bson.*;
import org.bson.codecs.*;
import org.bson.codecs.configuration.*;
import org.bson.io.*;
import org.bson.json.*;
import org.bson.types.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class BsonToJsonConverter {
public static void main(String[] args) throws IOException {
// -------------------------------------------------
// 1. Initialise file paths and JSON writer settings
// -------------------------------------------------
String inputPath = "collection.bson";
String outputPath = "collection.json";
JsonWriterSettings settings = JsonWriterSettings.builder()
.indent(true) // pretty‑print JSON
.build();
DocumentCodec codec = new DocumentCodec();
// -------------------------------------------------
// 2. Open the BSON file and prepare a writer for JSON
// -------------------------------------------------
try (FileInputStream fis = new FileInputStream(inputPath);
FileChannel channel = fis.getChannel();
FileWriter writer = new FileWriter(outputPath)) {
// -------------------------------------------------
// 3. Allocate a buffer the exact size of the file
// -------------------------------------------------
ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
channel.read(buffer);
buffer.flip(); // ready for reading
// -------------------------------------------------
// 4. Wrap the buffer for BSON reading
// -------------------------------------------------
try (ByteBufferBsonInput bsonInput = new ByteBufferBsonInput(new ByteBufNIO(buffer));
BsonBinaryReader reader = new BsonBinaryReader(bsonInput)) {
writer.write("[\n"); // start of JSON array
boolean first = true;
// -------------------------------------------------
// 5. Iterate over each BSON document in the buffer
// -------------------------------------------------
while (buffer.hasRemaining()) {
// Stop when we hit the end‑of‑document marker
if (reader.readBsonType() == BsonType.END_OF_DOCUMENT) {
break;
}
if (!first) {
writer.write(",\n"); // separate JSON objects
}
// Decode BSON → Document → JSON
Document doc = codec.decode(reader, DecoderContext.builder().build());
writer.write(doc.toJson(settings));
first = false;
}
writer.write("\n]"); // end of JSON array
System.out.println("Conversion completed successfully: " + outputPath);
}
}
}
}
What the Code Does
| Step | Description |
|---|---|
| 1. Initialise | Sets the input (collection.bson) and output (collection.json) file names, configures pretty‑printed JSON output, and creates a DocumentCodec for BSON → Document conversion. |
| 2. Open Files | Opens a FileInputStream for the BSON file, obtains a FileChannel for fast I/O, and creates a FileWriter for the JSON result. |
| 3. Allocate Buffer | Allocates a ByteBuffer sized exactly to the BSON file, reads the whole file into memory, and flips the buffer to prepare for reading. |
| 4. Wrap Buffer | Wraps the ByteBuffer in a ByteBufferBsonInput and creates a BsonBinaryReader to navigate the binary BSON structure. |
| 5. Iterate & Convert | Loops while the buffer has remaining bytes, stops at END_OF_DOCUMENT, decodes each BSON document into a Document, then writes the formatted JSON string to the output file. |
| Finish | Closes the JSON array, prints a success message, and automatically releases all resources via try‑with‑resources. |
How to Run
- Place the BSON file in the root directory of your Maven project (same level as
pom.xml). - Execute the following Maven command:
mvn clean compile exec:java
| Goal | Purpose |
|---|---|
clean | Deletes the target folder. |
compile | Compiles the Java source. |
exec:java | Runs the main method of BsonToJsonConverter. |
After the build finishes, collection.json will appear alongside your BSON file.
Why This Is Useful
- Quick format conversion – Turn binary BSON dumps into human‑readable JSON without needing a running MongoDB instance.
- Developer tooling – Use the MongoDB Java driver to inspect or query collections programmatically before exporting.
- Automation‑ready – Integrate this snippet into build pipelines or scripts for batch processing of multiple BSON files.