【问题标题】:How to write a Java code which renders nice looking colored HTML from JSON formatted code? [closed]如何编写从 JSON 格式的代码呈现漂亮的彩色 HTML 的 Java 代码? [关闭]
【发布时间】:2021-01-13 18:01:58
【问题描述】:

对于我们的 API,我们希望在一些专用于它的页面(即销售页面)上显示 JSON 示例。

所以它需要很好地格式化,使用颜色的 span。

我们可以使用JavaScript code prettifier,但该项目已存档,不再维护。

我们如何使用 Java 从美化的 JSON 代码生成漂亮的 HTML?

【问题讨论】:

    标签: java html json


    【解决方案1】:

    我们确实浏览了 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("&nbsp;");
          } 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();
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-03
      • 1970-01-01
      • 2023-02-19
      相关资源
      最近更新 更多