Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 146 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,30 @@
# JSON Experimental - JDK 21+ Backport
# java.util.json Backport for JDK 21+

This repository contains a backport of the experimental JSON API from the [jdk-sandbox project](https://github.com/openjdk/jdk-sandbox) to JDK 21 and later.
Early access to the future `java.util.json` API - tracking OpenJDK sandbox development.

## Origin
## Project Vision

This code is derived from the official OpenJDK sandbox repository at commit [d22dc2ba89789041c3908cdaafadc1dcf8882ebf](https://github.com/openjdk/jdk-sandbox/commit/d22dc2ba89789041c3908cdaafadc1dcf8882ebf) ("Improve hash code spec wording").
This project provides Java developers with early access to the future `java.util.json` API patterns today, allowing code written against this API to migrate seamlessly when the official API is released. Rather than adopting third-party JSON libraries that will never align with future JDK standards, developers can start using tomorrow's API patterns today.

## Current Status

This code is derived from the official OpenJDK sandbox repository at commit [d22dc2ba89789041c3908cdaafadc1dcf8882ebf](https://github.com/openjdk/jdk-sandbox/commit/d22dc2ba89789041c3908cdaafadc1dcf8882ebf) (3 days ago - "Improve hash code spec wording").

The original proposal and design rationale can be found in the included PDF: [Towards a JSON API for the JDK.pdf](Towards%20a%20JSON%20API%20for%20the%20JDK.pdf)

## Project Goals

- **Enable early adoption**: Let developers use future Java JSON patterns today on JDK 21+
- **Smooth migration path**: Code written against this API should require minimal changes when migrating to the official release
- **API compatibility over performance**: Focus on matching the API design rather than competing with existing JSON libraries on speed

## Non-Goals

- **Performance competition**: This is not intended to be the fastest JSON library
- **Feature additions**: No features beyond what's in the official sandbox/preview
- **Production optimization**: The official implementation will have JVM-level optimizations unavailable to a backport
- **API stability**: This backport may evolve as the official specification develops (if folks find it useful)

## Modifications

This is a simplified backport with the following changes from the original:
Expand Down Expand Up @@ -79,4 +96,128 @@ The conversion mappings are:
This is useful for:
- Integrating with existing code that uses standard collections
- Serializing/deserializing to formats that expect Java types
- Working with frameworks that use reflection on standard types
- Working with frameworks that use reflection on standard types

## Usage Examples

### Record Mapping

The most powerful feature is mapping between Java records and JSON:

```java
// Domain model using records
record User(String name, String email, boolean active) {}
record Team(String teamName, List<User> members) {}

// Create a team with users
Team team = new Team("Engineering", List.of(
new User("Alice", "[email protected]", true),
new User("Bob", "[email protected]", false)
));

// Convert records to JSON
JsonValue teamJson = Json.fromUntyped(Map.of(
"teamName", team.teamName(),
"members", team.members().stream()
.map(u -> Map.of(
"name", u.name(),
"email", u.email(),
"active", u.active()
))
.toList()
));

// Parse JSON back to records
JsonObject parsed = (JsonObject) Json.parse(teamJson.toString());
Team reconstructed = new Team(
((JsonString) parsed.members().get("teamName")).value(),
((JsonArray) parsed.members().get("members")).values().stream()
.map(v -> {
JsonObject member = (JsonObject) v;
return new User(
((JsonString) member.members().get("name")).value(),
((JsonString) member.members().get("email")).value(),
((JsonBoolean) member.members().get("active")).value()
);
})
.toList()
);
```

### Building Complex JSON

Create structured JSON programmatically:

```java
// Building a REST API response
JsonObject response = JsonObject.of(Map.of(
"status", JsonString.of("success"),
"data", JsonObject.of(Map.of(
"user", JsonObject.of(Map.of(
"id", JsonNumber.of(12345),
"name", JsonString.of("John Doe"),
"roles", JsonArray.of(List.of(
JsonString.of("admin"),
JsonString.of("user")
))
)),
"timestamp", JsonNumber.of(System.currentTimeMillis())
)),
"errors", JsonArray.of(List.of())
));
```

### Stream Processing

Process JSON arrays efficiently with Java streams:

```java
// Filter active users from a JSON array
JsonArray users = (JsonArray) Json.parse(jsonArrayString);
List<String> activeUserEmails = users.values().stream()
.map(v -> (JsonObject) v)
.filter(obj -> ((JsonBoolean) obj.members().get("active")).value())
.map(obj -> ((JsonString) obj.members().get("email")).value())
.toList();
```

### Error Handling

Handle parsing errors gracefully:

```java
try {
JsonValue value = Json.parse(userInput);
// Process valid JSON
} catch (JsonParseException e) {
// Handle malformed JSON with line/column information
System.err.println("Invalid JSON at line " + e.getLine() +
", column " + e.getColumn() + ": " + e.getMessage());
}
```

### Pretty Printing

Format JSON for display:

```java
JsonObject data = JsonObject.of(Map.of(
"name", JsonString.of("Alice"),
"scores", JsonArray.of(List.of(
JsonNumber.of(85),
JsonNumber.of(90),
JsonNumber.of(95)
))
));

String formatted = Json.toDisplayString(data, 2);
// Output:
// {
// "name": "Alice",
// "scores": [
// 85,
// 90,
// 95
// ]
// }
```
4 changes: 2 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>JSON Experimental</name>
<description>Experimental JSON API and internal dependencies</description>
<name>java.util.json Backport for JDK 21+</name>
<description>Early access to future java.util.json API - tracking OpenJDK sandbox development</description>

<licenses>
<license>
Expand Down
Loading