Skip to content

Commit e653d31

Browse files
committed
feat: improve machine assisted discovery and usage
- Converted public API Javadoc from /** */ to /// markdown format - Added comprehensive usage examples to README.md with focus on record mapping - Created ReadmeDemoTests.java with all README examples as tested code - Examples cover: record mapping, JSON building, stream processing, error handling, and pretty printing - All examples are tested and working (21 tests passing)
1 parent 971b729 commit e653d31

File tree

7 files changed

+787
-304
lines changed

7 files changed

+787
-304
lines changed

README.md

Lines changed: 125 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,4 +79,128 @@ The conversion mappings are:
7979
This is useful for:
8080
- Integrating with existing code that uses standard collections
8181
- Serializing/deserializing to formats that expect Java types
82-
- Working with frameworks that use reflection on standard types
82+
- Working with frameworks that use reflection on standard types
83+
84+
## Usage Examples
85+
86+
### Record Mapping
87+
88+
The most powerful feature is mapping between Java records and JSON:
89+
90+
```java
91+
// Domain model using records
92+
record User(String name, String email, boolean active) {}
93+
record Team(String teamName, List<User> members) {}
94+
95+
// Create a team with users
96+
Team team = new Team("Engineering", List.of(
97+
new User("Alice", "[email protected]", true),
98+
new User("Bob", "[email protected]", false)
99+
));
100+
101+
// Convert records to JSON
102+
JsonValue teamJson = Json.fromUntyped(Map.of(
103+
"teamName", team.teamName(),
104+
"members", team.members().stream()
105+
.map(u -> Map.of(
106+
"name", u.name(),
107+
"email", u.email(),
108+
"active", u.active()
109+
))
110+
.toList()
111+
));
112+
113+
// Parse JSON back to records
114+
JsonObject parsed = (JsonObject) Json.parse(teamJson.toString());
115+
Team reconstructed = new Team(
116+
((JsonString) parsed.members().get("teamName")).value(),
117+
((JsonArray) parsed.members().get("members")).values().stream()
118+
.map(v -> {
119+
JsonObject member = (JsonObject) v;
120+
return new User(
121+
((JsonString) member.members().get("name")).value(),
122+
((JsonString) member.members().get("email")).value(),
123+
((JsonBoolean) member.members().get("active")).value()
124+
);
125+
})
126+
.toList()
127+
);
128+
```
129+
130+
### Building Complex JSON
131+
132+
Create structured JSON programmatically:
133+
134+
```java
135+
// Building a REST API response
136+
JsonObject response = JsonObject.of(Map.of(
137+
"status", JsonString.of("success"),
138+
"data", JsonObject.of(Map.of(
139+
"user", JsonObject.of(Map.of(
140+
"id", JsonNumber.of(12345),
141+
"name", JsonString.of("John Doe"),
142+
"roles", JsonArray.of(List.of(
143+
JsonString.of("admin"),
144+
JsonString.of("user")
145+
))
146+
)),
147+
"timestamp", JsonNumber.of(System.currentTimeMillis())
148+
)),
149+
"errors", JsonArray.of(List.of())
150+
));
151+
```
152+
153+
### Stream Processing
154+
155+
Process JSON arrays efficiently with Java streams:
156+
157+
```java
158+
// Filter active users from a JSON array
159+
JsonArray users = (JsonArray) Json.parse(jsonArrayString);
160+
List<String> activeUserEmails = users.values().stream()
161+
.map(v -> (JsonObject) v)
162+
.filter(obj -> ((JsonBoolean) obj.members().get("active")).value())
163+
.map(obj -> ((JsonString) obj.members().get("email")).value())
164+
.toList();
165+
```
166+
167+
### Error Handling
168+
169+
Handle parsing errors gracefully:
170+
171+
```java
172+
try {
173+
JsonValue value = Json.parse(userInput);
174+
// Process valid JSON
175+
} catch (JsonParseException e) {
176+
// Handle malformed JSON with line/column information
177+
System.err.println("Invalid JSON at line " + e.getLine() +
178+
", column " + e.getColumn() + ": " + e.getMessage());
179+
}
180+
```
181+
182+
### Pretty Printing
183+
184+
Format JSON for display:
185+
186+
```java
187+
JsonObject data = JsonObject.of(Map.of(
188+
"name", JsonString.of("Alice"),
189+
"scores", JsonArray.of(List.of(
190+
JsonNumber.of(85),
191+
JsonNumber.of(90),
192+
JsonNumber.of(95)
193+
))
194+
));
195+
196+
String formatted = Json.toDisplayString(data, 2);
197+
// Output:
198+
// {
199+
// "name": "Alice",
200+
// "scores": [
201+
// 85,
202+
// 90,
203+
// 95
204+
// ]
205+
// }
206+
```

README_EXAMPLES_PLAN.md

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
# README Examples Plan
2+
3+
## Goal
4+
Show practical, real-world usage patterns that demonstrate the unique value of this JSON API, focusing on:
5+
1. Type-safe record mapping (the killer feature for modern Java)
6+
2. Pattern matching with sealed types
7+
3. Efficient conversion between Java types and JSON
8+
9+
## Proposed Examples Structure
10+
11+
### 1. Quick Start (Keep existing basic example)
12+
```java
13+
JsonValue value = Json.parse(jsonString);
14+
```
15+
16+
### 2. Pattern Matching with JSON Types
17+
Show how the sealed type hierarchy enables elegant pattern matching:
18+
```java
19+
// Processing unknown JSON structure
20+
JsonValue value = Json.parse(response);
21+
String result = switch (value) {
22+
case JsonObject obj -> processUser(obj);
23+
case JsonArray arr -> processUsers(arr);
24+
case JsonString str -> "Message: " + str.value();
25+
case JsonNumber num -> "Count: " + num.toNumber();
26+
case JsonBoolean bool -> bool.value() ? "Active" : "Inactive";
27+
case JsonNull n -> "No data";
28+
};
29+
```
30+
31+
### 3. Record Mapping Pattern
32+
The most valuable use case - mapping JSON to/from Java records:
33+
34+
```java
35+
// Domain model using records
36+
record User(String name, String email, boolean active) {}
37+
record Team(String teamName, List<User> members) {}
38+
39+
// Convert records to JSON
40+
Team team = new Team("Engineering", List.of(
41+
new User("Alice", "[email protected]", true),
42+
new User("Bob", "[email protected]", false)
43+
));
44+
45+
JsonValue teamJson = Json.fromUntyped(Map.of(
46+
"teamName", team.teamName(),
47+
"members", team.members().stream()
48+
.map(u -> Map.of(
49+
"name", u.name(),
50+
"email", u.email(),
51+
"active", u.active()
52+
))
53+
.toList()
54+
));
55+
56+
// Parse JSON back to records
57+
JsonObject parsed = (JsonObject) Json.parse(teamJson.toString());
58+
Team reconstructed = new Team(
59+
((JsonString) parsed.members().get("teamName")).value(),
60+
((JsonArray) parsed.members().get("members")).values().stream()
61+
.map(v -> {
62+
JsonObject member = (JsonObject) v;
63+
return new User(
64+
((JsonString) member.members().get("name")).value(),
65+
((JsonString) member.members().get("email")).value(),
66+
((JsonBoolean) member.members().get("active")).value()
67+
);
68+
})
69+
.toList()
70+
);
71+
```
72+
73+
### 4. Builder Pattern for Complex JSON
74+
Show how to build complex JSON structures programmatically:
75+
```java
76+
// Building a REST API response
77+
JsonObject response = JsonObject.of(Map.of(
78+
"status", JsonString.of("success"),
79+
"data", JsonObject.of(Map.of(
80+
"user", JsonObject.of(Map.of(
81+
"id", JsonNumber.of(12345),
82+
"name", JsonString.of("John Doe"),
83+
"roles", JsonArray.of(List.of(
84+
JsonString.of("admin"),
85+
JsonString.of("user")
86+
))
87+
)),
88+
"timestamp", JsonNumber.of(System.currentTimeMillis())
89+
)),
90+
"errors", JsonArray.of(List.of())
91+
));
92+
```
93+
94+
### 5. Streaming/Processing Pattern
95+
Show how to process large JSON arrays efficiently:
96+
```java
97+
// Process a large array of records
98+
JsonArray items = (JsonArray) Json.parse(largeJsonArray);
99+
List<String> activeUserEmails = items.values().stream()
100+
.map(v -> (JsonObject) v)
101+
.filter(obj -> ((JsonBoolean) obj.members().get("active")).value())
102+
.map(obj -> ((JsonString) obj.members().get("email")).value())
103+
.toList();
104+
```
105+
106+
### 6. Error Handling
107+
Show how to handle parsing errors and invalid data:
108+
```java
109+
try {
110+
JsonValue value = Json.parse(userInput);
111+
// Process valid JSON
112+
} catch (JsonParseException e) {
113+
// Handle malformed JSON
114+
System.err.println("Invalid JSON at line " + e.getLine() + ": " + e.getMessage());
115+
}
116+
```
117+
118+
## What NOT to Include
119+
- Basic JSON syntax explanation
120+
- Full coverage of JSON spec
121+
- Overly simple examples that don't show real value
122+
- Complex examples that obscure the API's simplicity
123+
124+
## Focus Areas
125+
1. **Record mapping** - This is what modern Java developers want
126+
2. **Pattern matching** - Leverages Java 21+ features
127+
3. **Type safety** - Show how compile-time safety prevents runtime errors
128+
4. **Real-world patterns** - REST API responses, configuration parsing, data transformation

0 commit comments

Comments
 (0)