From 58adb2d63dd98cc4f4bf18b47417320ab80c50ae Mon Sep 17 00:00:00 2001 From: Pablo Herrera Date: Sat, 16 Mar 2024 14:31:55 +0100 Subject: [PATCH] Improve json detection for formatted text 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) {