【发布时间】:2021-01-13 18:01:58
【问题描述】:
对于我们的 API,我们希望在一些专用于它的页面(即销售页面)上显示 JSON 示例。
所以它需要很好地格式化,使用颜色的 span。
我们可以使用JavaScript code prettifier,但该项目已存档,不再维护。
我们如何使用 Java 从美化的 JSON 代码生成漂亮的 HTML?
【问题讨论】:
对于我们的 API,我们希望在一些专用于它的页面(即销售页面)上显示 JSON 示例。
所以它需要很好地格式化,使用颜色的 span。
我们可以使用JavaScript code prettifier,但该项目已存档,不再维护。
我们如何使用 Java 从美化的 JSON 代码生成漂亮的 HTML?
【问题讨论】:
我们确实浏览了 Stackoverflow 和 Google,但找不到解决方案。所以我们最终自己编写。
我决定发布我们在这里使用的代码(供其他人作为参考):
public static String getHtmlFromButifiedJson(String json) {
StringBuilder result = new StringBuilder();
//0 - no markup
//1 - markup for numbers etc
//2 - markup for puncation
//3 - markup for "strings"
int currentOption = 0;
for (char c : json.toCharArray()) {
if (c == '\n') {
result.append("<br/>\n");
} else if (c == ' ') {
result.append(" ");
} else if (Character.isAlphabetic(c) || Character.isDigit(c)) {
if (currentOption == 0) {
currentOption = 1;
result.append("<span class=\"markup_numbers\">");
}
result.append(c);
} else if (c == ',' || c == '[' || c == ']' || c == '{' || c == '}' || c == ':') {
if (currentOption == 1) {
currentOption = 0;
result.append("</span>");
}
if (currentOption == 3) {
result.append(c);
} else {
result.append("<span class=\"markup_punct\">").append(c).append("</span>");
}
} else if (c == '\"') {
if (currentOption == 3) {
currentOption = 0;
result.append("\"</span>");
} else if (currentOption == 0) {
currentOption = 3;
result.append("<span class=\"markup_strings\">\"");
} else {
throw new RuntimeException("invalid json");
}
} else {
result.append(c);
}
}
return result.toString();
}
【讨论】: