java - 我们如何将 json 发送到 Controller 并基于 java 中的键进行迭代?

标签 java spring-mvc

下面是我的 JSON:

{
    "key1" : "10.5",
    "key2" : "20.5",
    "key3" : "10.5",
    "key4" : "20.5",
    "key5" : "10.5"
}

我想在调用邮政服务时将此 Json 发送到 Controller 类,并且我想根据类中的键迭代 json。我们如何在我们的类中接收 json 以及我们如何迭代。

我做了以下:

@PostMapping("/api/v1/save")
public String save_commodities_user_predict_data(@RequestBody String jsonData) {

    System.out.println("jsonData:"+jsonData); 

}

在控制台中,我得到以下输出:

jsonData:{
    "key1" : "10.5",
    "key2" : "20.5",
    "key3" : "10.5",
    "key4" : "20.5",
    "key5" : "10.5"
}

现在,我如何迭代 jsonData 并根据我的 java 类中的键获取值?

请澄清。

最佳答案

将参数类型更改为 Map<String, String>并遍历 map 。如果您有理由不能这样做,则必须将字符串解析为 json。

@PostMapping("/api/v1/save")
public String save_commodities_user_predict_data(@RequestBody Map<String, String> jsonData) {

    for (Entry<String,String> pair : jsonData.entrySet()){
        //iterate over the pairs
        System.out.println(pair.getKey()+" "+pair.getValue());
    }
}

关于java - 我们如何将 json 发送到 Controller 并基于 java 中的键进行迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53652999/

相关文章:

java - 使用 Weblogic WLST 创建托管服务器

java - 是否可以使用 java 更改现有 kafka 主题的复制因子?

java - 无法将属性从 Controller 传递到 View

java - 为什么 Spring DispatcherServlet 找不到我的 Controller 方法?

java - Thymeleaf 使用路径变量到 :href

java - Sonar 中的单元测试执行时间非常长

java - 使用服务方法调用 servlet 的 init 和 destroy 方法

java - Spring 中的 @Service 与 @Component

javascript - 如何返回 ModelandView 文件和字符串?

spring - Gradle无法创建可行的 jar