如何接收 dto,其中地图作为其属性之一,作为控制器的参数?(REST API)



当我尝试发送它时,它显示了"错误"; "trace"……HttpMessageNotReadableException: JSON解析错误:Cannot deserialize Map key of type ofjava.time.LocalDatefrom String "quoteDate" Failed to deserialize java.time.LocalDate">

我通过邮递员发送的JSON:

{
"stockId":"test3",
"quotes":[
{
"quoteDate":"2003-05-14",
"quoteValue":"35.9"
},
{
"quoteDate":"2016-03-28",
"quoteValue":"55.0"
}
]
}

控制器:

@PostMapping("/stock/save")
public void saveQuotes(@RequestBody StockDTO stockDTO) {
System.out.println(stockDTO.toString());
}
DTO

public class StockDTO {
String id;
String stockId;
Map<LocalDate, Double> quotes;
}

对于引号,根据json字符串应该出现的数据类型是List。但在DTO拿到了一张地图
DTO应为::

import com.google.gson.Gson;
import java.util.List;
public class GsonMappingExample {
public static void main(String[] args) {
String jsonString = "{"stockId":"test3","quotes":[{"quoteDate":"2003-05-14","quoteValue":"35.9"},{"quoteDate":"2016-03-28","quoteValue":"55.0"}]}";
Gson gson = new Gson();
StockDTO stockDTO = gson.fromJson(jsonString, StockDTO.class);
System.out.println(stockDTO);
}
}
class StockDTO {
private final String stockId;
private final List<Quote> quotes;
public StockDTO(String stockId, List<Quote> quotes) {
this.stockId = stockId;
this.quotes = quotes;
}
@Override
public String toString() {
return "StockDTO{" +
"stockId='" + stockId + ''' +
", quoteList=" + quotes +
'}';
}
}
class Quote {
private final String quoteDate;
private final Double quoteValue;
public Quote(String quoteDate, Double quoteValue) {
this.quoteDate = quoteDate;
this.quoteValue = quoteValue;
}
@Override
public String toString() {
return "Quote{" +
"quoteDate=" + quoteDate +
", quoteValue=" + quoteValue +
'}';
}
}

PS:这里我使用Gson库来解析json字符串,spring-boot自动做到这一点(使用Jackson库我认为!)

相关内容

  • 没有找到相关文章

最新更新