【问题标题】:Pretty printing JSON with Grails Views使用 Grails 视图漂亮地打印 JSON
【发布时间】:2019-07-10 18:43:02
【问题描述】:

在使用 Grails Views 库进行 JSON 输出(及其扩展名为 .gson 的模板文件)时,是否可以漂亮地打印 JSON 输出?

背景:我正在使用 Grails Views 1.3.0(目前在 Grails 3.1.16 上)进行数据导出/通过 JsonViewTemplateEngine 将复杂的 JSON 树渲染到文件中(参见 Grails Views documentation 的第 2.11 章)。

我可能向 Google 提出了错误的问题,但我还没有找到解决方法(无需解析/重新呈现 JSON 输出,效率不高),并且大多数现有信息都与 JSON 相关转换器,但不是 Grails JSON 视图...任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: json grails


    【解决方案1】:

    您在创建 GsonBuilder 时使用setPrettyPrinting:

    public class GsonExample {
    
        public static void main(String[] args) {
    
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
    
            String[] lang = {"Value One", "Value Two"};
    
            String json = gson.toJson(lang);
    
            System.out.println(json);
    
        }
    
    }
    

    将 Gson 配置为输出适合页面的 Json 印刷。此选项仅影响 Json 序列化。

    你可以找到它的文档here。

    【讨论】:

    • 看起来这个答案是针对另一个库而不是针对 Grails Views。我猜 GSON 参考在我原来的问题中可能有点令人困惑,因为它只指在 Grails 中使用 .gson 扩展名的模板文件。我将编辑问题以使文件扩展名更加明显。
    【解决方案2】:

    对于 Grails 4,我正在这样做,然后将值呈现为我的 GSP 中的常规字符串/变量。 Grails 的 GSON 应该类似地工作。

    当您想要显示原始 JSON 时,CSS white-space: pre 属性可以在浏览器中提供帮助。

    def json = x as JSON
    json.prettyPrint = true;
    log.info(json.toString())
    

    【讨论】:

      猜你喜欢
      • 2015-07-03
      • 2015-08-26
      • 2023-04-04
      • 2013-10-03
      • 2011-08-05
      相关资源
      最近更新 更多