【问题标题】:Play Framework - how to walk tree of JsonNode in view?Play Framework - 如何在视图中遍历 JsonNode 树?
【发布时间】:2015-04-10 23:22:06
【问题描述】:

您好,我正在尝试在视图中显示嵌套的 JSON 数据,类似于当您从 API 获得响应时它在 Advanced REST Client 中的显示方式。

我找到了this question,它基本上问的是我问的问题;但是,我想使用 Play Framework 2.3.x 在视图中显示结果。我知道我需要一个递归函数来显示所有 json 对象,所以我尝试在我的视图中使用可重用块。这是我现在拥有的:

@(fromAPI: com.fasterxml.jackson.databind.JsonNode)

@import com.fasterxml.jackson.databind.JsonNode

@walkJsonTree(name: String, node: JsonNode) = {

    @if(node.isObject()) {

        @for(nodeEntry <- node.fields()) {
            <li>@nodeEntry.getKey(): </li>
            <ul>@walkJsonTree(nodeEntry.getKey(), nodeEntry.getValue())</ul>
        }
    }
    @if(node.isArray()) {
        @for(arrayNode <- node.fields()) {
            <li>[List]: </li>
            <ul>@walkJsonTree(arrayNode.getKey(), arrayNode.getValue())</ul>
        }
    }
    @if(node.isValueNode()) {
        <li>@node.asText()</li>
    } else {
        @* other *@
        <li>@node.asText()</li>
    }

}

@main("API Response") {

    <div class="container">
        <h3>API Response</h3>

        <ul>
            @walkJsonTree(null, fromAPI)
        </ul>
    </div>
}

很遗憾,这无法正确显示 JSON。它仅显示基于此行&lt;li&gt;@nodeEntry.getKey(): &lt;/li&gt; 的第一个对象的名称。我究竟做错了什么? 是否有人对以嵌套方式显示 JSON 有任何其他建议?

谢谢!

【问题讨论】:

    标签: json playframework playframework-2.3 twirl


    【解决方案1】:

    我的“数组”if 块错误。它应该使用elements() 函数而不是fields()。这是我的代码的更新版本,其中包含 &lt;ul&gt;&lt;li&gt; 元素的重构和其他清理

    @(fromAPI: com.fasterxml.jackson.databind.JsonNode)
    
    @import com.fasterxml.jackson.databind.JsonNode
    
    @walkJsonTree(name: String, node: JsonNode) = {
    
        @if(node.isObject()) {
            <ul>
                @for(nodeEntry <- node.fields()) {
                    <li>@nodeEntry.getKey(): @walkJsonTree(nodeEntry.getKey(), nodeEntry.getValue())</li>
                }
            </ul>
        }
        @if(node.isArray()) {
            <ul>
                @for(arrayNode <- node.elements()) {
                    <li>[List]: @walkJsonTree(name, arrayNode)</li>
                }
            </ul>
        }
        @if(node.isValueNode()) {
            @node.asText()
        } else {
            @* other *@
            @node.asText()
        }
    
    }
    
    @main("API Response") {
    
        <div class="container">
            <h3>API Response</h3>
            @walkJsonTree(null, fromAPI) 
        </div>
    }
    

    这在美学上可能仍然可以改进,但它满足了我想要的最低功能

    【讨论】:

      猜你喜欢
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多