From aa50c40070ffc58d501d00c89e26bd0a51748654 Mon Sep 17 00:00:00 2001 From: Pablo Herrera Date: Sat, 13 Apr 2024 04:07:18 +0700 Subject: [PATCH] Improve json detection for formatted text (#1309) Signed-off-by: Pablo Herrera --- util/src/main/java/tc/oc/pgm/util/text/TextParser.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/util/src/main/java/tc/oc/pgm/util/text/TextParser.java b/util/src/main/java/tc/oc/pgm/util/text/TextParser.java index 1bfcbcf65b..d9b15d32cc 100644 --- a/util/src/main/java/tc/oc/pgm/util/text/TextParser.java +++ b/util/src/main/java/tc/oc/pgm/util/text/TextParser.java @@ -45,6 +45,9 @@ private TextParser() {} private static final Pattern INF = Pattern.compile("^((\\+|-)?oo)$", Pattern.CASE_INSENSITIVE); private static final Pattern DOT = Pattern.compile("\\s*\\.\\s*"); private static final Pattern COMMA = Pattern.compile("\\s*,\\s*"); + // [{ "prop" : ... }], {prop: ...} or ['prop': ...}, looks like json, but could be invalid + private static final Pattern PROBABLY_JSON = + Pattern.compile("[\\[{][ \\[{]*\\s*([\"']?)\\w+\\1\\s*:.*[\\[}]+", Pattern.CASE_INSENSITIVE); private static final Range NONNEG = Range.atLeast(0); /** @@ -413,7 +416,7 @@ public static LocalDate parseDate(String text) throws TextException { public static Component parseComponent(String text) throws TextException { assertNotNull(text, "cannot parse component from null"); - if (text.startsWith("{\"") && text.endsWith("\"}")) { + if (PROBABLY_JSON.matcher(text).matches()) { try { return GsonComponentSerializer.gson().deserialize(text); } catch (JsonSyntaxException e) { @@ -444,7 +447,7 @@ public static Component parseComponent(String text) throws TextException { public static Component parseComponentSection(String text) { assertNotNull(text, "cannot parse component from null"); - if (text.startsWith("{\"") && text.endsWith("\"}")) { + if (PROBABLY_JSON.matcher(text).matches()) { try { return GsonComponentSerializer.gson().deserialize(text); } catch (Throwable t) {