@@ -486,42 +486,31 @@ public static Json of(String jsonString) {
486
486
final var result = new HashMap <String , Object >();
487
487
final var matcher = keyPattern .matcher (jsonString );
488
488
while (matcher .find ()) {
489
- final var key = matcher .group (1 );
490
- final var value = parseValue (matcher .group (2 ));
491
- result .put (key , value );
489
+ result .put (matcher .group (1 ), parseValue (matcher .group (2 )));
492
490
}
493
491
return new Json (result );
494
492
}
495
493
496
494
private static Object parseValue (final String textValue ) {
497
- if (textValue .startsWith ("\" " ) && textValue .endsWith ("\" " )) {
498
- return textValue .substring (1 , textValue .length () - 1 );
499
- } else if ("true" .equals (textValue )) {
500
- return true ;
501
- } else if ("false" .equals (textValue )) {
502
- return false ;
503
- } else if ("null" .equals (textValue )) {
504
- return null ;
505
- } else if (textValue .indexOf ('.' ) >= 0 ) {
506
- return Double .parseDouble (textValue );
507
- } else if (textValue .startsWith ("{" )) {
508
- return of (textValue );
509
- } else {
510
- return Long .parseLong (textValue );
511
- }
512
- }
513
-
514
- /** Sample: {@code json.get("a.b.c")} */
495
+ return switch (textValue ) {
496
+ case "true" -> true ;
497
+ case "false" -> false ;
498
+ case "null" -> null ;
499
+ default -> textValue .charAt (0 ) == '"' && textValue .charAt (textValue .length () - 1 ) == '"'
500
+ ? textValue .substring (1 , textValue .length () - 1 )
501
+ : textValue .indexOf ('.' ) >= 0 ? Double .parseDouble (textValue )
502
+ : textValue .startsWith ("{" ) ? of (textValue )
503
+ : Long .parseLong (textValue );
504
+ };
505
+ }
506
+
507
+ /** Get a value by the (composite) key. For example: {@code json.get("a.b.c").get()} */
515
508
public Optional <Object > get (String keys ) {
516
- var json = this ;
517
509
var result = (Object ) null ;
510
+ var json = this ;
518
511
for (var key : keys .split ("\\ ." )) {
519
512
result = json .map .get (key );
520
- if (result instanceof Json j ) {
521
- json = j ;
522
- } else {
523
- Optional .empty ();
524
- }
513
+ json = (result instanceof Json j ) ? j : new Json (Map .of ());
525
514
}
526
515
return Optional .ofNullable (result );
527
516
}
0 commit comments