如何转义 json-stylished String 以使用 MessageFormat?

How to escape json-stylished String to work with MessageFormat?

我正在使用 并且以下代码片段中断,因为 MessageFormat 获取 JSON 符号,例如 {} 并将它们解释为它自己的格式化程序防止要格式化的字符串:

import java.math.BigDecimal;
import java.text.MessageFormat;

public class Test {

    public static void main(final String[] args) {
        System.out.println(MessageFormat.format("""
                {
                    "a": "{0}",
                 {
                  "b": "{0}"
                  "c": "{0}"
                  "d": {1,number,#.##}
                 }
                }""", "Test", new BigDecimal("10.123")));
    }
}

这是堆栈跟踪:

Exception in thread "main" java.lang.IllegalArgumentException: can't parse argument number: 
    "a": "{0}"
    at java.base/java.text.MessageFormat.makeFormat(MessageFormat.java:1454)
    at java.base/java.text.MessageFormat.applyPattern(MessageFormat.java:492)
    at java.base/java.text.MessageFormat.<init>(MessageFormat.java:371)
    at java.base/java.text.MessageFormat.format(MessageFormat.java:860)
    at Test.main(Test.java:9)
Caused by: java.lang.NumberFormatException: For input string: "
    "a": "{0}""
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:654)
    at java.base/java.lang.Integer.parseInt(Integer.java:786)
    at java.base/java.text.MessageFormat.makeFormat(MessageFormat.java:1452)
    ... 4 more

转义这些符号以便 MessageFormat 实际格式化字符串的正确方法是什么?

Java 17 中的语法不应有任何更改,因为 MessageFormat 是 Java 7 中的 known。 正如过去在这里引用的那样: Accepted answer for Question #1187093

Within a String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, pattern string "'{0}'" represents string "{0}", not a FormatElement.