【发布时间】:2019-07-24 14:21:30
【问题描述】:
在 Spring Boot 的 REST 控制器中,我试图迭代 RequestBody 响应中的值,并将其中一些值放入 POST 端点的 HashMap 中。
我发送的 JSON 是这样的结构:
{"name":"yogurt","vitaminA":6,"vitaminb12":5}
到目前为止,端点看起来像这样:
@RequestMapping("/create")
public NutrientList createNUtrientList(@RequestBody NutrientList nutrientList) {
Map<String, Double> nutrientMap = new HashMap<String,Double>();
//get nutrient values, need help with this part
for()
//add values to map
NutrientList nl = new NutrientList(nutrientList.getName(), nutrientMap);
//will save to repository
return nl;
}
NutrientList 类如下所示:
public class NutrientList {
@Id
private ObjectId id;
@JsonProperty("name")
private String name;
@JsonProperty("nutrientMap")
Map <String,Double> nutrientMap = new HashMap<String,Double>();
public NutrientList() {}
public NutrientList(String name, Map<String, Double> nutrientMap) {
this.id = new ObjectId();
this.name = name;
this.nutrientMap = nutrientMap;
}
//setters and getters
}
数据以单独的营养素存储在数据库中,不是地图。我看到 NutrientList 类不共享相同的结构,但有什么办法可以解决这个问题,以便能够使用地图而不改变它在数据库中的存储方式?
我需要使用地图,因为有很多营养素,我不想为它们设置单独的变量。太感谢了。如果有不清楚的地方请告诉我。
编辑: 我可以交替地将我从数据库中获取数据的 csv 转换为带有地图的 JSON 格式,但我还没有找到一个在线工具可以给我这种灵活性。
【问题讨论】:
-
感谢您的资源,但我不是想循环地图,而是将响应正文制作成地图。
-
您确定请求正文是 NutrientList 吗?好像和你展示的Json字符串不一样。
-
是的,它是不同的,但有什么办法可以解决这个问题?
-
我可以将参数更改为什么?
标签: json mongodb spring-boot spring-restcontroller