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));
}
}
上面的代碼打?。?/p>
[ {
"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>
添加回答
舉報