2 回答
TA贡献1851条经验 获得超4个赞
序列化上述实例列表的最经典方法POJO是将其序列化为数组。
import com.fasterxml.jackson.databind.ObjectMapper;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
public class MapperApp {
public static void main(String[] args) throws Exception {
List<CoefficientPerQuantityParameter> coefficients = Arrays.asList(new CoefficientPerQuantityParameter(2, BigDecimal.valueOf(0.9)),
new CoefficientPerQuantityParameter(10, BigDecimal.valueOf(0.8)),
new CoefficientPerQuantityParameter(40, BigDecimal.valueOf(0.7)));
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(coefficients));
}
}
上面的代码打印:
[ {
"hour" : 2,
"cost" : 0.9
}, {
"hour" : 10,
"cost" : 0.8
}, {
"hour" : 40,
"cost" : 0.7
} ]
如果您想拥有一个结构,其中hour是键和cost值,我建议将给定数组转换为Map手动并序列化结果。
import com.fasterxml.jackson.databind.ObjectMapper;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class MapperApp {
public static void main(String[] args) throws Exception {
List<CoefficientPerQuantityParameter> coefficients = Arrays.asList(new CoefficientPerQuantityParameter(2, BigDecimal.valueOf(0.9)),
new CoefficientPerQuantityParameter(10, BigDecimal.valueOf(0.8)),
new CoefficientPerQuantityParameter(40, BigDecimal.valueOf(0.7)));
Map<Integer, BigDecimal> map = coefficients.stream()
.collect(Collectors.toMap(CoefficientPerQuantityParameter::getHour, CoefficientPerQuantityParameter::getCost));
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map));
}
}
上面的代码打印:
{
"2" : 0.9,
"40" : 0.7,
"10" : 0.8
}
TA贡献1784条经验 获得超8个赞
另一种方法是使用th:inline="javascript". 您仍然需要将数据转换为 aMap<String, Double>以获得所需的输出布局。例如:
控制器
List<CoefficientPerQuantityParameter> list = Arrays.asList(
new CoefficientPerQuantityParameter(2, BigDecimal.valueOf(0.9)),
new CoefficientPerQuantityParameter(10, BigDecimal.valueOf(0.8)),
new CoefficientPerQuantityParameter(40, BigDecimal.valueOf(0.7))
);
Map<String, BigDecimal> map = list.stream().collect(Collectors.toMap(
o -> "" + o.getHour(),
CoefficientPerQuantityParameter::getCost)
);
模板
<span th:inline="javascript">[[${map}]]</span>
输出
<span>{"2":0.9,"40":0.7,"10":0.8}</span>
添加回答
举报