Arnab Ghosh
Arnab Ghosh

Reputation: 113

Input a JSONArray into swagger API for a springboot controller

I am new to using springboot and swagger, so not very familiar with this stuff. But what I want to do is to input a JSONArray into a swagger API and get the input into a controller. So, I have the following controller code:

@RestController
public class NameRegisterController{
  @Autowired
  private NameRegisterService service;
  
  @Postmapping(path="/control")
  public void NameRegisterAdd(@RequestParam JSONArray NameList)
  {
    service.addNames(NameList);
  }
}

Here, addNames is a function which takes JSONArray as input. When I go to the swagger API, I add the input as:

["name1","name2","name3"]

Unfortunately, when I execute, I get the error

"ConversionFailedException: Failed to convert from type[java.lang.String] to type [@org.springframework.web.bind.RequestParam org.json.JSONArray] for value 'name1'; nested exception is org.json.JSONException: JSONArray test must start with '[' at 1 [character 2 line 1"

I don't get it because the first character of my input is "[" as put in the swagger API. Would be very grateful if someone can provide some help. My swagger is in my work environment, so am inserting similar pictures from the internet.

This is what I get This is what I want

The first pic is what I get. The second pic is what I want

Upvotes: 0

Views: 1398

Answers (1)

jcompetence
jcompetence

Reputation: 8383

String Array

Frontend Pass with HTTP request

[“a”,”b”,”c”]

Backend receive in controller methods

@RequestParam String[] ids
@RequestParam List<String> ids

And I dont see you defining which request parameter name it should be looking at?

Example:

public String inputControllerMethod(@RequestParam(value="myParam") List<String> myParam){

}

=== Edited ===

You can't.

Using the [Add String Item] button you must insert 1 String at a time.

However if they are not Strings, but rather an Array of Objects, then swagger allows you to write the array:

enter image description here

Use this https://editor.swagger.io/#/ to see an example.

Documentation: https://swagger.io/docs/specification/2-0/describing-parameters/

Your other option also if you really dont want the user to enter and you are limited by specific options is an enum:

parameters:
  - name: "status"
    in: "query"
    description: "Status values that need to be considered for filter"
    required: true
    type: "array"
    items:
      type: "string"
      enum:
        - "placed"
        - "approved"

Then the user simply selects multiple/all options:

enter image description here

Upvotes: 1

Related Questions