Skip to content

Commit a9befc8

Browse files
committed
JSON code cleaning
1 parent 2ae2317 commit a9befc8

File tree

1 file changed

+16
-27
lines changed

1 file changed

+16
-27
lines changed

utils/PPUtils.java

Lines changed: 16 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -486,42 +486,31 @@ public static Json of(String jsonString) {
486486
final var result = new HashMap<String, Object>();
487487
final var matcher = keyPattern.matcher(jsonString);
488488
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)));
492490
}
493491
return new Json(result);
494492
}
495493

496494
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()} */
515508
public Optional<Object> get(String keys) {
516-
var json = this;
517509
var result = (Object) null;
510+
var json = this;
518511
for (var key : keys.split("\\.")) {
519512
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());
525514
}
526515
return Optional.ofNullable(result);
527516
}

0 commit comments

Comments
 (0)