Mustache Java: Iterating over an anonymous/keyless/top-level array

淺唱寂寞╮ 提交于 2019-12-13 07:58:28

问题


Question: How to iterate over an array read from json input, that does not have a variable name/key. I did not want to restructure the json file as I'd have to edit the service which generates this json and also other services rely on this file and would have also been affected.

A solution for javascript has already been posted using "." as array name in the Mustache template: Can mustache iterate a top-level array? and here Iterate over keyless array with mustache?

I had the same question for the java implementation of Mustache.

Again, an example of input data (json):

[ 
{
  "name" : "test",
  "week" : "first",
  "date" : "Wed Oct 02 14:06:35 GMT 2019",
  "status" : "success"
}
]

回答1:


Reading this with Jackson into a map and then converting it back to a json string showed me that Jackson will name this array "object". Here's an output of that conversion and reconversion:

{
  "object" : [ {
    "name" : "test",
    "week" : "first",
    "date" : "Wed Oct 02 14:06:35 GMT 2019",
    "status" : "success"
  } ]
}

So if you use Jackson, we can simply use the identifier "object" in the Mustache template

    {{#object}}
    <tr>
        <td>{{name}}</td>
        <td>{{week}}</td>
        <td>{{date}}</td>
        <td>{{status}}</td>
    </tr>
    {{/object}}


来源:https://stackoverflow.com/questions/58235839/mustache-java-iterating-over-an-anonymous-keyless-top-level-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!