How to calculate the sum of variables from JSON data?

时间秒杀一切 提交于 2021-02-05 12:29:14

问题


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

@PostMapping("/reverse")
public String reverseList(@RequestBody String string) {
    List<String> stringList = Arrays.asList(string.split("[+,]"));
    return  IntStream.range(0, stringList.size())
            .mapToObj(i -> stringList.get(stringList.size() - 1 - i))
            .collect(Collectors.joining("+"));
}

Command through curl :

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

Output :

a4+a3+a2+a1

How can I change so that I can add values. For example, when returning  

а1 = 10
а2 = 10
a3 = 10

And when I write the command below :

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

It should return the sum as 30.


回答1:


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); 
}


来源:https://stackoverflow.com/questions/58556012/how-to-calculate-the-sum-of-variables-from-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!