2

So Let's say that I have an endpoint:

POST /answer

Currently It only receives one answer from user.

{
    "question": "3+5",
    "answer": "8"
}

I'm curious It is possible to receive multiple answers, for the same endpoint.

[
    {
        "question": "3+5",
        "answer": "8"
    },
    {
        "question": "9+3",
        "answer": "12"
    }
]

I'm using Spring Boot 1.5.1. Here's the controller code that I'm using:

@RequestMapping(value = "/answer", method = RequestMethod.POST)
public Response submitAnswer(SubmitAnswerRq rq) {
    return service.submitAnswer(rq);
}

Any ideas?

3
  • 1
    Why not (@RequestBody SubmitAnswerRq[] rq) Commented Oct 19, 2018 at 2:20
  • @LipingHuang I'll give it a try. Commented Oct 19, 2018 at 2:32
  • @LipingHuang Looks like the client should send the request in forms of array, even if It contains only one item in it. this is not what I wanted to do.. Commented Oct 19, 2018 at 3:01

2 Answers 2

2

Don't do this One answer is different from multi answers. Don't complicated simple things.

I recommend your write a new end point something like /multiAnswer

@RequestMapping(value = "/multiAnswer", method = RequestMethod.POST)
public Response submitAnswer(SubmitMultiAnswerRq rq) {
    return service.submitAnswer(rq);
}

public class SubmitMultiAnswerRq {
    private List<SubmitAnswerRq> answers;
    //getter and setter
}
Sign up to request clarification or add additional context in comments.

2 Comments

Well.. It is more clear and I tend to use this, but I'm just curious If it is possible.
Maybe is possible. I have no idea. Springmvc automatically converts json into an object. It is unreasonable to convert different jsons into same object.
1

Use List to receive as array..so when you have one question then send also under array:

[{
    "question": "3+5",
    "answer": "8"
}]

and same n numbers of answers you can send in request, make sure your service handle as a list and you should be good.

@RequestMapping(value = "/answer", method = RequestMethod.POST)
public Response submitAnswer(List<SubmitAnswerRq> rq) {
    return service.submitAnswer(rq);
}

1 Comment

Yes I can do that, but I was looking for something like Spring settings to mapping different input types for same endpoint. Besides, I use this approach for now. Thanks for reply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.