How to calculate the sum of variables from JSON data?

前端 未结 1 1522
走了就别回头了
走了就别回头了 2021-01-29 12:13

I wrote a project where the string is returned the other way around.

@PostMapping(\"/reverse\")
public String reverseList(@RequestBody String string) {
    List&         


        
1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-29 12:31

    Try to do this. It will make your work easier.

    Send a1=10+a2=10+a3=10 instead of a1+a2+a3 in the curl command.

    Command :

    curl -H "Content-Type: application/json" -d "a1=10+a2=10+a3=10" localhost:8080/hello/reverse
    

    Update the code to this :

    @PostMapping("/reverse")
    public String reverseList(@RequestBody String str) {
        int sum = 0;
        String[] variables = str.split("\\+");
        for (String variable : variables) {
            sum += Integer.parseInt(variable.split("=")[1]);
        }
        return String.valueOf(sum); 
    }
    

    0 讨论(0)
提交回复
热议问题