1+ package jdk .sandbox .java .util .json .examples ;
2+
3+ import jdk .sandbox .java .util .json .*;
4+
5+ import java .util .List ;
6+ import java .util .Map ;
7+
8+ /**
9+ * Standalone examples demonstrating the java.util.json API.
10+ * This file contains runnable examples that match the README documentation.
11+ *
12+ * To run:
13+ * mvn compile exec:java -Dexec.mainClass="jdk.sandbox.java.util.json.examples.ReadmeExamples"
14+ */
15+ public class ReadmeExamples {
16+
17+ // Domain model using records
18+ record User (String name , String email , boolean active ) {}
19+ record Team (String teamName , List <User > members ) {}
20+
21+ public static void main (String [] args ) {
22+ System .out .println ("=== Java.util.json API Examples ===\n " );
23+
24+ quickStartExample ();
25+ recordMappingExample ();
26+ builderPatternExample ();
27+ streamingProcessingExample ();
28+ errorHandlingExample ();
29+ displayFormattingExample ();
30+
31+ System .out .println ("\n === All examples completed successfully! ===" );
32+ }
33+
34+ static void quickStartExample () {
35+ System .out .println ("1. Quick Start Example" );
36+ System .out .println ("----------------------" );
37+
38+ // Basic parsing example
39+ String jsonString = "{\" name\" :\" Alice\" ,\" age\" :30}" ;
40+ JsonValue value = Json .parse (jsonString );
41+
42+ System .out .println ("Parsed JSON: " + jsonString );
43+ System .out .println ("Value type: " + value .getClass ().getSimpleName ());
44+
45+ JsonObject obj = (JsonObject ) value ;
46+ String name = ((JsonString ) obj .members ().get ("name" )).string ();
47+ long age = ((JsonNumber ) obj .members ().get ("age" )).toLong ();
48+
49+ System .out .println ("Extracted name: " + name );
50+ System .out .println ("Extracted age: " + age );
51+ System .out .println ("Round trip: " + value .toString ());
52+ System .out .println ();
53+ }
54+
55+ static void recordMappingExample () {
56+ System .out .println ("2. Record Mapping Example" );
57+ System .out .println ("-------------------------" );
58+
59+ // Create a team with users
60+ Team team = new Team ("Engineering" , List .of (
61+ new User ("Alice" , "alice@example.com" , true ),
62+ new User ("Bob" , "bob@example.com" , false )
63+ ));
64+
65+ System .out .println ("Original team: " + team );
66+
67+ // Convert records to JSON using typed factories
68+ JsonValue teamJson = JsonObject .of (Map .of (
69+ "teamName" , JsonString .of (team .teamName ()),
70+ "members" , JsonArray .of (team .members ().stream ()
71+ .map (u -> JsonObject .of (Map .of (
72+ "name" , JsonString .of (u .name ()),
73+ "email" , JsonString .of (u .email ()),
74+ "active" , JsonBoolean .of (u .active ())
75+ )))
76+ .toList ())
77+ ));
78+
79+ System .out .println ("JSON representation:" );
80+ System .out .println (teamJson .toString ());
81+
82+ // Parse JSON back to records
83+ JsonObject parsed = (JsonObject ) Json .parse (teamJson .toString ());
84+ Team reconstructed = new Team (
85+ ((JsonString ) parsed .members ().get ("teamName" )).string (),
86+ ((JsonArray ) parsed .members ().get ("members" )).elements ().stream ()
87+ .map (v -> {
88+ JsonObject member = (JsonObject ) v ;
89+ return new User (
90+ ((JsonString ) member .members ().get ("name" )).string (),
91+ ((JsonString ) member .members ().get ("email" )).string (),
92+ ((JsonBoolean ) member .members ().get ("active" )).bool ()
93+ );
94+ })
95+ .toList ()
96+ );
97+
98+ System .out .println ("Reconstructed team: " + reconstructed );
99+ System .out .println ("Round trip successful: " + team .equals (reconstructed ));
100+ System .out .println ();
101+ }
102+
103+ static void builderPatternExample () {
104+ System .out .println ("3. Builder Pattern Example" );
105+ System .out .println ("-------------------------" );
106+
107+ // Building a REST API response
108+ JsonObject response = JsonObject .of (Map .of (
109+ "status" , JsonString .of ("success" ),
110+ "data" , JsonObject .of (Map .of (
111+ "user" , JsonObject .of (Map .of (
112+ "id" , JsonNumber .of (12345 ),
113+ "name" , JsonString .of ("John Doe" ),
114+ "roles" , JsonArray .of (List .of (
115+ JsonString .of ("admin" ),
116+ JsonString .of ("user" )
117+ ))
118+ )),
119+ "timestamp" , JsonNumber .of (System .currentTimeMillis ())
120+ )),
121+ "errors" , JsonArray .of (List .of ())
122+ ));
123+
124+ System .out .println ("API Response:" );
125+ System .out .println (Json .toDisplayString (response , 2 ));
126+ System .out .println ();
127+ }
128+
129+ static void streamingProcessingExample () {
130+ System .out .println ("4. Streaming Processing Example" );
131+ System .out .println ("--------------------------------" );
132+
133+ // Create a large array of user records
134+ String largeJsonArray = """
135+ [
136+ {"name": "Alice", "email": "alice@example.com", "active": true},
137+ {"name": "Bob", "email": "bob@example.com", "active": false},
138+ {"name": "Charlie", "email": "charlie@example.com", "active": true},
139+ {"name": "David", "email": "david@example.com", "active": false},
140+ {"name": "Eve", "email": "eve@example.com", "active": true}
141+ ]
142+ """ ;
143+
144+ // Process a large array of records
145+ JsonArray items = (JsonArray ) Json .parse (largeJsonArray );
146+ List <String > activeUserEmails = items .elements ().stream ()
147+ .map (v -> (JsonObject ) v )
148+ .filter (obj -> ((JsonBoolean ) obj .members ().get ("active" )).bool ())
149+ .map (obj -> ((JsonString ) obj .members ().get ("email" )).string ())
150+ .toList ();
151+
152+ System .out .println ("Active user emails: " + activeUserEmails );
153+ System .out .println ();
154+ }
155+
156+ static void errorHandlingExample () {
157+ System .out .println ("5. Error Handling Example" );
158+ System .out .println ("------------------------" );
159+
160+ // Valid JSON parsing
161+ String validJson = "{\" valid\" : true}" ;
162+ try {
163+ JsonValue value = Json .parse (validJson );
164+ System .out .println ("Valid JSON parsed successfully: " + value );
165+ } catch (JsonParseException e ) {
166+ System .out .println ("Unexpected error: " + e .getMessage ());
167+ }
168+
169+ // Invalid JSON parsing
170+ String invalidJson = "{invalid json}" ;
171+ try {
172+ JsonValue value = Json .parse (invalidJson );
173+ System .out .println ("This shouldn't print" );
174+ } catch (JsonParseException e ) {
175+ System .out .println ("Caught expected error: " + e .getMessage ());
176+ System .out .println ("Error at line " + e .getErrorLine () + ", position " + e .getErrorPosition ());
177+ }
178+ System .out .println ();
179+ }
180+
181+ static void displayFormattingExample () {
182+ System .out .println ("6. Display Formatting Example" );
183+ System .out .println ("-----------------------------" );
184+
185+ // Create a structured JSON
186+ JsonObject data = JsonObject .of (Map .of (
187+ "name" , JsonString .of ("Alice" ),
188+ "scores" , JsonArray .of (List .of (
189+ JsonNumber .of (85 ),
190+ JsonNumber .of (90 ),
191+ JsonNumber .of (95 )
192+ ))
193+ ));
194+
195+ // Format for display
196+ String formatted = Json .toDisplayString (data , 2 );
197+ System .out .println ("Formatted JSON:" );
198+ System .out .println (formatted );
199+ System .out .println ();
200+ }
201+ }
0 commit comments